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

时间:2018-01-07 01:30:15

标签: javascript arrays node.js object ecmascript-6

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

{
    "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 env > = 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
  }

})

2 个答案:

答案 0 :(得分:1)

您可以使用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)




答案 1 :(得分:0)

您可以使用filtermap。如果obj是您的初始对象,那么您可以执行以下操作:

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