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

69
我有一个对象数组。 我正在按照以下方式在数组中搜索。

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)

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

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

它仅返回第一个匹配的行。

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

我不想使用任何外部库来实现这个功能。如何返回所有符合条件的匹配项?

6个回答

108

两件事情:首先,Array.find()返回第一个匹配的元素,如果它找不到任何内容,则返回undefinedArray.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);


2
正是我所寻找的。 - Mike Victoria

10

使用数组筛选方法。例如

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

3

需要使用filter方法替代find。这将返回一个新数组,其中只包含从传入函数返回真实值的成员。


3
Array.prototype.find()方法根据MDN规范:返回数组中第一个满足提供的测试函数的元素的值。

你应该使用filter函数.filter()代替,它将返回一个包含所有与您的测试函数匹配的实例的数组。


-3

使用filtercharAt

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

2
如果你想匹配数字42,知道会发生什么吗?使用item.arrayWithvalue.charAt(0)是一个不好的建议。 - Orelsanpls

-3
使用 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);


那么,如果你想匹配数字42,知道会发生什么吗?使用e.arrayWithvalue.split(',')[0]是个不好的建议。 - Orelsanpls

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接