gpt4 book ai didi

javascript - 过滤具有多个属性的多个数组对象

转载 作者:搜寻专家 更新时间:2023-10-30 21:04:26 25 4
gpt4 key购买 nike

我正在尝试创建一个过滤器函数,它可以从给定的字符串键集中返回与我正在寻找的值匹配的数据结果

数组示例:

let data = [
{ id:1 , data:{ name:"sample1",address:{ cat:"business" } } },
{ id:2 , data:{ name:"sample2",address:{ cat:"office" } } },
{ id:3 , data:{ name:"sample3",address:{ cat:"office" } } },
{ id:4 , data:{ name:"sample4",address:{ cat:"office" } } }
{ id:5 , data:{ name:"sample5",address:{ cat:"home" } } }
{ id:6 , data:{ name:"sample6",address:{ cat:"home" } } }
]



function filter( collection , value ,key ){
//code
}


let result = filter( data , "business" , [ "data","address","cat" ] )

console.log(result)

预期结果是

{ id:1 , data:{ name:"sample1",address:{ cat:"business" } } },

最佳答案

您可以使用filter 来搜索数据。使用 reduce 构造键。

注意:filter 返回匹配元素的数组。如果您只喜欢第一个匹配项,则可以使用 find

const data = [
{ id: 1, data: { name: "sample1", address:{ cat: "business" } } },
{ id: 2, data: { name: "sample2", address:{ cat: "office" } } },
{ id: 3, data: { name: "sample3", address:{ cat: "office" } } },
{ id: 4, data: { name: "sample4", address:{ cat: "office" } } },
{ id: 5, data: { name: "sample5", address:{ cat: "home" } } },
{ id: 6, data: { name: "sample6", address:{ cat: "home" } } }
]

const filter = (collection, keys, value) =>
collection.filter(o => keys.reduce((c, v) => c[v] || {}, o) === value)
const result = filter(data, ["data", "address", "cat"], "business")

console.log(result)

关于javascript - 过滤具有多个属性的多个数组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50595907/

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