如何基于ID筛选对象数组?

3
我有一个对象数组,我想循环遍历它并根据传入函数的id或code进行过滤。请保留HTML标签。
state.products = [{id = 1, name = Bottle},{id = 2, name = umbrella}, {id = 3, name = shoe}]

const getVal = (id)=> {

 const av = state.products.filter((s) s.productId == id)

}

以下代码似乎没有遍历数组并检查每个对象?我在console.log(av)中得到一个空数组。

2
state.products.filter((s) => s.id == id) - Dhaval Marthak
1个回答

2
你正在走正确的道路,但你没有正确使用 Array.filter
此外,提供的对象数组格式也不够好。对象应该是 键:值对。
state.products = [
    { id: 1, name: "Bottle" },
    { id: 2, name: "umbrella" },
    { id: 3, name: "shoe" }
]

const getAllArrayExcept = (id) => {
    // this will return all the array except provided id
    return state.products.filter((s) => s.id !== id)
}

const getOnlyArray = (id) => {
    // this will return only item which match the provided id
    return state.products.filter((s) => s.id === id)
}

console.log(getAllArrayExcept(1))
/*
output: [{ id = 2, name = umbrella }, { id = 3, name = shoe }]
*/
console.log(getOnlyArray(1))
/*
output: [{ id = 1, name = Bottle }]
*/

这里是可用的代码片段:

const products = [
    { id: 1, name: "Bottle" },
    { id: 2, name: "umbrella" },
    { id: 3, name: "shoe" }
]

const getAllArrayExcept = (id) => {
    // this will return all the array except provided id
    return products.filter((s) => s.id !== id)
}

const getOnlyArray = (id) => {
    // this will return only item which match the provided id
    return products.filter((s) => s.id === id)
}

console.log("All array except: ", getAllArrayExcept(1))
console.log("Only provided item in array: ", getOnlyArray(1))


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接