gpt4 book ai didi

基于多个条件的javascript对象过滤器

转载 作者:行者123 更新时间:2023-12-03 02:45:06 25 4
gpt4 key购买 nike

我有以下对象,我想根据某些属性对其进行过滤并仅输出其中的某些部分。

{
"email" : "john.doe@acme.com",
"name" : " John Doe",
"groups" : [
{
"name" : "group1",
"country": "US",
"contacts" : [
{ "localId" : "c1", "address" : "some address 1" },
{ "localId" : "c2", "address" : "some address 2" },
{ "localId" : "c3", "address" : "some address 3" }
]
},
{
"name" : "group2",
"country": "Canada",
"contacts" : [
{ "localId" : "c1", "address" : "some address 1" },
{ "localId" : "c3", "address" : "some address 3" }
]
}
]
}

结果应该是这样的:

{
"email" : "john.doe@acme.com",
"name" : " John Doe",
"groups" : [
{
"name" : "group1",
"country": "US",
"contacts" : [
{
"localId" : "c3",
"address" : "some address 3"
}
]
}
]
}

所以我的条件是:

groups.name="group1"
groups.contacts.localId="c3"

如何使用一些 ecma6 js 函数来实现它?内存负载最少?我在nodejs环境>=8.9.0

更新:

这是我失败的尝试:

const conditions = {"groups.name": "group1", "groups.contacts.localId": "c3"};
let res = mylist.map((i)=>{
return {
email: i.email,
name: i.name,
groupsName: conditions.groups.name
}

})

最佳答案

您可以使用 filter() 相当简洁地完成此操作。如果您首先过滤群组名称,您就不会浪费时间过滤联系人:

let obj = {
"email": "john.doe@acme.com",
"name": " John Doe",
"groups": [{
"name": "group1",
"country": "US",
"contacts": [{
"localId": "c1",
"address": "some address 1"
},
{
"localId": "c2",
"address": "some address 2"
},
{
"localId": "c3",
"address": "some address 3"
}
]
},
{
"name": "group2",
"country": "Canada",
"contacts": [{
"localId": "c1",
"address": "some address 1"
},
{
"localId": "c3",
"address": "some address 3"
}
]
}
]
}

let newObj = {
"email": obj.email,
"name": obj.name,
"groups": obj.groups.filter(item => item.name == "group1").map(g => (g.contacts = g.contacts.filter(c => c.localId == "c3"), g))
}
console.log(newObj)

关于基于多个条件的javascript对象过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48133563/

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