查找对象数组中所有与之匹配的元素 [英] Find all matching elements with in an array of objects
问题描述
我有一个对象数组
我正在像这样在数组中搜索
I am searching within the array like this
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)
这应该返回一个包含这两行的数组
This should return an array with this two rows
{ name:"string 2", arrayWithvalue:"4,5", other: "that" },
{ name:"string 2", arrayWithvalue:"4", other: "that" }
它仅返回一行,这是第一个匹配项.
It returns only one row which is the first match.
{ name:"string 2", arrayWithvalue:"4", other: "that" }
我不想为此使用任何外部库.如何返回所有符合条件的匹配项?
I do not want to use any external libraries for this. How can I return all the matches that match the criteria?
推荐答案
首先,Array.find()
返回第一个匹配元素,undefined
,如果找不到任何内容. Array.filter
返回一个包含所有匹配元素的新数组,如果[]
不匹配任何内容.
Two thing, first, Array.find()
return the first matching element, undefined
if it finds nothing. Array.filter
returns a new array containing all matching elements, []
if it matches nothing.
第二件事,如果要匹配4,5
,则必须查看字符串,而不要进行严格的比较.为了实现这一点,我们使用indexOf
返回匹配字符串的位置,或者使用-1
如果什么都不匹配.
Second thing, if you want to match 4,5
, you have to look into the string and do not make strict comparaison. To make that happens we use of indexOf
which is returning the position of the matching string, or -1
if it matches nothing.
示例:
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);
这篇关于查找对象数组中所有与之匹配的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!