过滤搜索所有键值对的对象数组

时间:2018-07-18 02:20:23

标签: javascript

假设我在JavaScript中有一个对象数组,看起来像这样:

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'},
];

如果我想将上述数组中包含“ Tanya”值的对象过滤到一个新数组中,该如何处理?新数组如下所示:

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

3 个答案:

答案 0 :(得分:2)

您正在寻找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)

答案 1 :(得分:2)

这是一个简短的解决方案,需要Object.valuescaniuse?):

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);

答案 2 :(得分:0)

使用includes会容易得多。

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);