gpt4 book ai didi

javascript - 如何根据数组中的元素进行过滤?

转载 作者:行者123 更新时间:2023-11-28 12:12:47 25 4
gpt4 key购买 nike

我有以下多个数组,如下所示:

//Condition one
var categorys = [1, 2];

//useType = 0,Return useType=0 element

//useType = 1,Returns the same categorys element as c_id

var data = [
{c_id:0, name:'phone', useType:0},
{c_id:1, name: "milk", useType:1},
{c_id:2, name: "apple", useType:1},
{c_id:3, name: "orang", useType:1},
{c_id:4, name: "red", useType:1}
]

我做了以下尝试:

let result = data.filter((item, index) => {
if(item.useType === 0) {
return true
} else if(item.useType === 1 && item.c_id === categorys[index]){
return true
}
else {
return false
}
});

我想得到以下结果

[
{c_id:0, name:'phone',useType:0},
{c_id:1, name: "milk",useType:1},
{c_id:2, name: "apple",useType:1}
]

但我只能得到一个

[
{c_id:0, name:'phone',useType:0},
]

你能帮我吗?

最佳答案

您可以使用Array.prototype.includes()检查 categories 数组是否包含特定的 c_id 值:

const categories = [1, 2];

const data = [
{c_id: 0, name: "phone", useType: 0},
{c_id: 1, name: "milk", useType: 1},
{c_id: 2, name: "apple", useType: 1},
{c_id: 3, name: "orang", useType: 1},
{c_id: 4, name: "red", useType: 1}
];

const result = data.filter(({useType, c_id}) =>
useType === 0 || useType === 1 && categories.includes(c_id));

console.log(result);

关于javascript - 如何根据数组中的元素进行过滤?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57423162/

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