I have the following object and I want to filter it based on some properties and output only some parts of it.
{
"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" }
]
}
]
}
the result should look like:
{
"email" : "john.doe@acme.com",
"name" : " John Doe",
"groups" : [
{
"name" : "group1",
"country": "US",
"contacts" : [
{
"localId" : "c3",
"address" : "some address 3"
}
]
}
]
}
So my conditions are:
groups.name="group1"
groups.contacts.localId="c3"
how can I achieve it using some ecma6 js function? with the least memory load? I am in nodejs env >=8.9.0 .
here is my failing attempt:
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
}
})
You can do this fairly succinctly with filter()
. If you filter on group name first you won't waste time filtering the contacts:
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)
You can use filter
and map
. If obj
is your initial object then you can do:
obj.groups = obj.groups.filter((g)=>g.name==="group1")
for(int i = 0; i < obj.groups.length;i++)
{
obj.groups[i].contacts = obj.groups[i].contacts.filter((c)=>c.localId==="c3"))
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.