gpt4 book ai didi

arrays - 根据内部数组条件查找数组中的项目

转载 作者:太空狗 更新时间:2023-10-29 19:36:36 26 4
gpt4 key购买 nike

如何在对象数组内部的数组中查找 id

例子:

let arrayobjects = [{ 
id: 1,
name: "oinoin",
description: ["one", "two", "three"]
}, {
id: 2,
name: "zatata",
description: ["four", "five", "six"]
}];

如何找到单词“二”的id?

最佳答案

如果需要不止一项,可以通过Array#filter过滤数组,通过 Array#includes 检查每个项目的属性 description 是否包含单词 two (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);

关于arrays - 根据内部数组条件查找数组中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51651449/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com