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

Find all matching elements with in an array of objects

我有一个对象数组

我正在这样的数组中搜索

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)

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

{ name:"string 2", arrayWithvalue:"4,5", other: "that" },
{ name:"string 2", arrayWithvalue:"4", other: "that" }

它 return 只有一行是第一个匹配项。

{ name:"string 2", arrayWithvalue:"4", other: "that" }

我不想为此使用任何外部库。我怎样才能 return 所有符合条件的匹配项?

filter and charAt.

const result = arr.filter(item => item.arrayWithvalue.charAt(0) === '4');

您需要使用 filter 方法代替 find。这将 return 一个新数组,仅包含 return 来自传入函数的真实值的成员。

两件事:首先,Array.find() returns 第一个匹配元素,undefined 如果没有找到。 Array.filter returns 包含所有匹配元素的新数组,[] 如果没有匹配项。

第二,如果你想匹配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);

Array.prototype.find() 将根据 MDN spec: return 满足提供的测试函数的数组中第一个元素的值.

您要使用的是 filter function .filter(),它将 return 一个包含与您的测试函数匹配的所有实例的数组。

使用array.filter:

var 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 res = arr.filter(e => e.arrayWithvalue.split(',')[0] === '4');
console.log(res);

使用数组过滤方法。 喜欢

arr.filter(res => res.arrayWithvalue.indexOf('4') !== -1);