我有一个对象数组
我正在像这样在数组中搜索
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" }
我不想为此使用任何外部库。如何返回所有符合条件的匹配项?
答案 0 :(得分:6)
两件事,首先,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);
答案 1 :(得分:1)
您需要使用filter
方法来代替find
。这将返回一个新数组,其中仅包含从传入函数中返回真实值的成员。
答案 2 :(得分:1)
Array.prototype.find()
将按照MDN spec:返回满足提供的测试功能的数组中第一个元素的值。
您要使用的是filter function .filter()
,它将返回与您的测试功能匹配的所有实例的数组。
答案 3 :(得分:1)
使用数组过滤器方法。 像
arr.filter(res => res.arrayWithvalue.indexOf('4') !== -1);
答案 4 :(得分:-1)
答案 5 :(得分:-1)
使用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);