简体   繁体   中英

How to filter object within an array that matches search object in Javascript

I am trying to filter and remove objects that are inside of my array however more objects are getting removed than I am hoping to target

const people = [
  {name: 'Adam', age: 30, country: 'USA'},
  {name: 'Carl', age: 30, country: 'UK'},
  {name: 'Bob', age: 40, country: 'China'},
 ];

const results = people.filter(element => {
  // 👇️ using AND (&&) operator
  return element.age !== 30 && element.name !== 'Carl';
});

console.log(results);

outputs:

[ { name: 'Bob', age: 40, country: 'China' } ]

I am hoping to only remove the object where Carl is found

My desired output would be

[ { name: 'Adam', age: 30, country: 'USA' }, { name: 'Bob', age: 40, country: 'China' } ]

You need to update the filter condition if you need to remove only 30yo Carls

return !(element.age === 30 && element.name === 'Carl');

which is equal to

return element.age !== 30 || element.name !== 'Carl';

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