gpt4 book ai didi

Javascript仅获取某个数组中包含的对象

转载 作者:行者123 更新时间:2023-12-01 00:51:24 25 4
gpt4 key购买 nike

我有一个数组

const dataitems =  [
{name:'test1', id:1},
{name:'test2', id:2},
{name:'test3', id:3}
]

const compares = [1,3]

所以我只想获取比较数组值中包含 id 的数据项的值

所以最后我希望得到一个最终数组

const ffinaldataitems =  [
{name:'test1', id:1},
{name:'test3', id:3}
]

排除 id 2

所以我尝试了以下方法,但卡住了

  let finaldataitems = []
dataitems.forEach(item=>{
if(item.id ) //stuck on how to check and push to the array
})

我该如何继续

最佳答案

您可以尝试使用 Array.prototype.filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Array.prototype.includes()

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

const dataitems =  [
{name:'test1', id:1},
{name:'test2', id:2},
{name:'test3', id:3}
];

const compares = [1,3];

let finaldataitems = dataitems.filter(item => compares.includes(item.id));

console.log(finaldataitems);

关于Javascript仅获取某个数组中包含的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56945081/

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