【问题标题】:如何根据 ID 过滤对象数组? [复制]
【发布时间】:2022-01-23 09:41:49
【问题描述】:

我有以下对象数组,我想遍历它并根据我传递给函数的 id 或代码进行过滤。

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) 的空数组

【问题讨论】:

  • state.products.filter((s) => s.id == id)

标签: javascript arrays reactjs filter javascript-objects


【解决方案1】:

您的方法正确,但您没有正确使用Array.filter

而且提供的对象数组也不是很好的格式。对象应位于key:value 对中。

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 }]
*/

这里是工作的 sn-p:

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))

【讨论】:

    猜你喜欢
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 2020-12-14
    • 1970-01-01
    • 2021-04-15
    相关资源
    最近更新 更多