查找对象数组中所有匹配的元素[重复]

2024-01-05

我有一个对象数组

我正在像这样的数组中搜索

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" }

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


两件事:第一,Array.find()返回第一个匹配元素,undefined如果什么也没发现。Array.filter返回一个包含所有匹配元素的新数组,[]如果没有匹配任何内容。

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


Example:

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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

查找对象数组中所有匹配的元素[重复] 的相关文章

随机推荐