Underscore Remove the Value without replace original variable

36 Views Asked by At

I have an array of objects and I'm trying to find the value in the object and remove the value has been found in the exist object. For example,

Current JSON Object:

exist=[{"x":6811,"y":15551,"a":["aa","ab","ac"]},{"x":6811,"y":15552,"a":["bb"]},{"x":6812,"y":15551,"a":["aa","cc"]}]

I want to find the "a" Key with value aa

The last result is

exist= [{"x":6811,"y":15552,"a":["bb"]}]
found= [{"x":6811,"y":15551,"a":["aa","ab","ac"]},{"x":6812,"y":15551,"a":["aa","cc"]}]
2

There are 2 best solutions below

4
ilsotov On

You can do it without underscore:

let exist= [
    { x: 6811, y: 15551, a: ['aa', 'ab', 'ac'] },
    { x: 6811, y: 15552, a: ['aa', 'bb'] },
    { x: 6812, y: 15551, a: ['cc'] },
];

const found = exist.filter(({ a }) => a.includes('aa'));
exist = exist.filter(({ a }) => !a.includes('aa'));

console.log('found:', found);
console.log('exist:', exist);

0
yvoytovych On

You can use .reject with .contains and _.result combination

exist=[
{"x":6811,"y":15551,"a":["aa","ab","ac"]},{"x":6811,"y":15552,"a":["bb"]},{"x":6812,"y":15551,"a":["aa","cc"]}, {"x":6812,"y":15551}
]

exist = _.reject(exist, function(item){ 
    return _.contains(_.result(item, "a"), "aa"); 
})

console.log(exist);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>