如何在对象数组内部的数组中查找id
例子:
let arrayobjects = [{
id: 1,
name: "oinoin",
description: ["one", "two", "three"]
}, {
id: 2,
name: "zatata",
description: ["four", "five", "six"]
}];
我怎么能找到“二”字的身份证?
最佳答案
如果需要多个项目,可以通过Array#filter筛选数组,检查每个项目的属性description
是否包含单词two
通过Array#includes(es7),然后使用Array#map映射结果以仅获取这些项目的id
。
let arrayobjects = [
{ id: 1, name: "oinoin", description: ["one", "two", "three"] },
{ id: 2, name: "zatata", description: ["four", "five", "six"] }
];
const ids = arrayobjects.filter(item => item.description.includes('two'))
.map(item => item.id);
console.log(ids);
如果你只有一个项目,你可以使用Array#find并做同样的检查。
let arrayobjects = [
{ id: 1, name: "oinoin", description: ["one", "two", "three"] },
{ id: 2, name: "zatata", description: ["four", "five", "six"] }
];
const item = arrayobjects.find(item => item.description.includes('two'));
console.log(item.id);