如何在数据项数组中搜索特定匹配项



我需要在下面提供的数组中进行搜索,这样当我搜索'002'pin值时,我应该得到'F02'area值。

[{
pin: "001",
area: "F01",
}, {
pin: "002",
area: "F02",
}, {
pin: "003",
area: "F07",
}, {
pin: "004",
area: "F08",
}]

使用array.filter:

filter((方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。

const arr = [{
pin: "001",
area: "F01",
}, {
pin: "002",
area: "F02",
}, {
pin: "003",
area: "F07",
}, {
pin: "004",
area: "F08",
}];
// the resulting array of a successful filter process.
console.log(
'the resulting array of a successful filter process ...',
arr.filter(i => i.pin === '002')
);
// accessing the `area` property of the first matching item.
console.log(
'accessing the `area` property of the first matching item ...',
arr.filter(i => i.pin === '002')[0].area
);
console.log('n');
// the resulting array of a non matching filter process.
console.log(
'the resulting array of a non matching filter process ...',
arr.filter(i => i.pin === '005')
);
// safely accessing the not assured first items's `area` property of an unknow filter result.
console.log(
"safely accessing the not assured first items's `area` property of an unknow filter result ...",
arr.filter(i => i.pin === '005')[0]?.area
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

使用array.find:

find((方法返回所提供数组中的第一个元素满足所提供的测试功能。如果没有值满足测试函数,返回undefined。

const arr = [{
pin: "001",
area: "F01",
}, {
pin: "002",
area: "F02",
}, {
pin: "003",
area: "F07",
}, {
pin: "004",
area: "F08",
}];
// object which satisfies the condition does exist.
console.log(
'object which satisfies the condition does exist ...',
arr.find(i => i.pin === '002')
);
// accessing the `area` property of the well known return value.
console.log(
'accessing the `area` property of the well known return value ...',
arr.find(i => i.pin === '002').area
);
console.log('n');
// object which satisfies the condition does not exist.
console.log(
'object which satisfies the condition does not exist ...',
arr.find(i => i.pin === '005')
);
// safely accessing the possible `area` property of a varying/unsafe return value.
console.log(
'safely accessing the possible `area` property of a varying/unsafe return value ...',
arr.find(i => i.pin === '005')?.area
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

如果您想找到特定的项目,请始终考虑使用array.find,因为它的最终目标是在array中找到单独的项目,但array.filter的目标是使用对array中的所有项目运行测试并返回通过项目。

Peter Seliger的重要提示:

find在条件匹配时立即停止迭代处理过的数组,而filter总是执行全循环

Array.find在您的情况下会有更好的性能速度并节省您的计算时间,因为array.find会立即返回您找到的项目,但array.filter会迭代array中的所有项目,无论是什么

You could just loop through the array and find the matches:
`var results = [];
var searchField = "pin";
var searchVal = "area";
for (var i=0 ; i < obj.list.length ; i++)
{
if (obj.list[i][searchField] == searchVal) {
results.push(obj.list[i]);
}
}`

最新更新