在对象数组中查找所有匹配的元素

ank*_*kur 4 javascript ecmascript-6 ecmascript-7

我有一个对象数组

我在这个数组中搜索

let arr = [
    { name:"string 1", arrayWithvalue:"1,2", other: "that" },
    { name:"string 2", arrayWithvalue:"2", other: "that" },
    { name:"string 2", arrayWithvalue:"2,3", other: "that" },
    { name:"string 2", arrayWithvalue:"4,5", other: "that" },
    { name:"string 2", arrayWithvalue:"4", other: "that" },
];
var item  = arr.find(item => item.arrayWithvalue === '4'); 
console.log(item)
Run Code Online (Sandbox Code Playgroud)

这应该返回一个包含这两行的数组

{ name:"string 2", arrayWithvalue:"4,5", other: "that" },
{ name:"string 2", arrayWithvalue:"4", other: "that" }
Run Code Online (Sandbox Code Playgroud)

它只返回一行,这是第一个匹配.

{ name:"string 2", arrayWithvalue:"4", other: "that" }
Run Code Online (Sandbox Code Playgroud)

我不想为此使用任何外部库.如何返回符合条件的所有匹配项?

Gré*_*EUT 12

两件事,首先,如果没有找到任何Array.find()内容,undefined则返回第一个匹配元素.Array.filter返回包含所有匹配元素的新数组([]如果它不匹配).

第二件事,如果你想匹配4,5,你必须查看字符串,不要进行严格的比较.为了实现这一点,我们使用的indexOf是返回匹配字符串的位置,或者-1它是否匹配.


示例:

  const arr = [{
    name: 'string 1',
    arrayWithvalue: '1,2',
    other: 'that',
  },
  {
    name: 'string 2',
    arrayWithvalue: '2',
    other: 'that',
  },
  {
    name: 'string 2',
    arrayWithvalue: '2,3',
    other: 'that',
  },
  {
    name: 'string 2',
    arrayWithvalue: '4,5',
    other: 'that',
  },
  {
    name: 'string 2',
    arrayWithvalue: '4',
    other: 'that',
  },
];

const items = arr.filter(item => item.arrayWithvalue.indexOf('4') !== -1);

console.log(items);
Run Code Online (Sandbox Code Playgroud)

  • 正是我正在寻找的, (2认同)

Ekl*_*vya 10

使用数组过滤方法。喜欢

arr.filter(res => res.arrayWithvalue.indexOf('4') !== -1);
Run Code Online (Sandbox Code Playgroud)