简体   繁体   中英

Filter an array of objects searching all key-value pairs

Let's say I have an array of objects in JavaScript that looks something like this:

namesArray = [
  { name: 'John', friend: 'Steve', brother: 'Jeff', sister: 'Karen'},
  { name: 'Sarah', friend: 'Joan', brother: 'Marvin', sister: 'Diana'},
  { name: 'Morris', friend: 'Tanya', brother: 'Mike', sister: 'Lisa'},
  { name: 'Brian', friend: 'Tim', brother: 'Andrew', sister: 'Tanya'},
];

If I wanted to filter out the objects in the above array that contain the value "Tanya" into a new array, how would I go about it? The new array would look like this:

newArray = [
  { name: 'Morris', friend: 'Tanya', brother: 'Mike', sister: 'Lisa'},
  { name: 'Brian', friend: 'Tim', brother: 'Andrew', sister: 'Tanya'},
];

You are looking for filter

 namesArray = [ { name: 'John', friend: 'Steve', brother: 'Jeff', sister: 'Karen'}, { name: 'Sarah', friend: 'Joan', brother: 'Marvin', sister: 'Diana'}, { name: 'Morris', friend: 'Tanya', brother: 'Mike', sister: 'Lisa'}, { name: 'Brian', friend: 'Tim', brother: 'Andrew', sister: 'Tanya'}, ]; const output = namesArray.filter(obj => Object.values(obj).findIndex(val => val === 'Tanya') > -1 ) console.log(output) 

Here's a short solution that requires Object.values ( caniuse? ):

 var namesArray = [ { name: 'John', friend: 'Steve', brother: 'Jeff', sister: 'Karen' }, { name: 'Sarah', friend: 'Joan', brother: 'Marvin', sister: 'Diana' }, { name: 'Morris', friend: 'Tanya', brother: 'Mike', sister: 'Lisa' }, { name: 'Brian', friend: 'Tim', brother: 'Andrew', sister: 'Tanya' }, ]; var tanyaOnly = namesArray.filter(e => Object.values(e).indexOf("Tanya") > -1); console.log(tanyaOnly); 

Use of includes would be much easier.

 const namesArray = [ { name: 'John', friend: 'Steve', brother: 'Jeff', sister: 'Karen'}, { name: 'Sarah', friend: 'Joan', brother: 'Marvin', sister: 'Diana'}, { name: 'Morris', friend: 'Tanya', brother: 'Mike', sister: 'Lisa'}, { name: 'Brian', friend: 'Tim', brother: 'Andrew', sister: 'Tanya'}, ]; let filteredArray = namesArray.filter(x => Object.values(x).includes('Tanya') === false); console.log(filteredArray); 

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