简体   繁体   中英

Filter out objects from another array in a loop

I have an allItems array of objects

allItems = [
    { id: 1, name: 'item1' },
    { id: 2, name: 'item2' },
    { id: 3, name: 'item3' }
]

I want it to filter out and not contain the objects contained in another array from my component.

fewItems = [
    { id: 2, name: 'item2' }
]

so, filteredItems should be :

filteredItems = [
    { id: 1, name: 'item1' },
    { id: 3, name: 'item3' }
]

And when another object from allItems is added to fewItems , it needs to disappear from the filteredItems one.

I would like to do this in pure vanilla JS, with no specific library.

Thanks ahead !

 var allItems = [ { id: 1, name: 'item1' }, { id: 2, name: 'item2' }, { id: 3, name: 'item3' } ]; var fewItems = [ { id: 2, name: 'item2' } ]; var result3 = _(allItems) .differenceBy(fewItems, 'id', 'name') .map(_.partial(_.pick, _, 'id', 'name')) .value(); console.log(result3); 
 <script src='https://cdn.jsdelivr.net/lodash/4.17.2/lodash.min.js'></script> 

EDIT

Without Lodash

 var allItems = [ { id: 1, name: 'item1' }, { id: 2, name: 'item2' }, { id: 3, name: 'item3' } ]; var fewItems = [ { id: 2, name: 'item2' } ]; var props = ['id', 'name']; var result = allItems.filter(function(o1){ return !fewItems.some(function(o2){ return o1.id === o2.id; }); }).map(function(o){ return props.reduce(function(newo, name){ newo[name] = o[name]; return newo; }, {}); }); console.log(result); 

 var allItems = [ { id: 1, name: 'item1' }, { id: 2, name: 'item2' }, { id: 3, name: 'item3' } ]; var fewItems = [ { id: 2, name: 'item2' } ]; var keys = Object.keys( fewItems[0] ) var result = allItems.filter( function(item){ for( var k = fewItems.length-1; k>=0; --k){ var dontWant = fewItems[k]; var i=keys.length-1; for( ; i>=0; --i ){ if( dontWant[keys[i]] != item[keys[i]]){ break; } } if( i == -1){ return false;} } return true; } ); console.log(result) 

Pure JS solution

 var allItems = [ { id: 1, name: 'item1' }, { id: 2, name: 'item2' }, { id: 3, name: 'item3' } ]; var fewItems = [ { id: 2, name: 'item2' } ]; var result3 = allItems .filter(item => { for(let restrictedItem of fewItems) { if (JSON.stringify(restrictedItem) === JSON.stringify(item)) { return false; } } return true; }) console.log(result3); 

filteredItems =  this.allItems.filter(x => {
    return !this.fewItems.some(y => JSON.stringify(y) == JSON.stringify(x))
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM