Lodash过滤嵌套的json

时间:2019-03-18 16:33:02

标签: node.js lodash

嗨,我有以下json数据...

    {
    "contacts":
    [
        {
            "contactId": "00001",
            "firstName": "test",
            "lastName": "test",
            "email": "test@test.com",
            "phone": "0207 0000000",
            "role": "Surveyor",
            "customer": "00001",
            "projects": [{"projId": "00002"}]
        },
        {
            "contactId": "00002",
            "firstName": "test1",
            "lastName": "test1",
            "email": "test@test.com",
            "phone": "0207 1111111",
            "role": "Manager",
            "customer": "00001",
            "projects": [{"projId": "00002"}, {"projId": "00003"}]
        }
    ]
}

我需要一个API端点,该端点返回基于projID的联系人,但是由于projId嵌套在项目数组中而出现问题...

    //Get contacts by Project
app.get('/v1/projcontacts/:id', function(req, res) {
    var id = req.params.id;
    var projContacts = lodash.filter(contactData.contacts, { 'projId': id });
    res.json(projContacts);
})

有人帮我使用上面的代码让lodash可以查看项目内部吗?

3 个答案:

答案 0 :(得分:1)

您可以尝试以下操作:

app.get('/v1/projcontacts/:id', function(req, res) {
  var id = req.params.id;
  var projContacts = contacts.filter(
    contact => contact.projects.map(
      projects => projects.projId === id
    ).includes(true)
  )
  res.json(projContacts);
})

答案 1 :(得分:1)

您可以尝试以下操作:


const data = {
    "contacts":
    [
        {
            "contactId": "00001",
            "firstName": "test",
            "lastName": "test",
            "email": "test@test.com",
            "phone": "0207 0000000",
            "role": "Surveyor",
            "customer": "00001",
            "projects": [{"projId": "00002"}]
        },
        {
            "contactId": "00002",
            "firstName": "test1",
            "lastName": "test1",
            "email": "test@test.com",
            "phone": "0207 1111111",
            "role": "Manager",
            "customer": "00001",
            "projects": [{"projId": "00002"}, {"projId": "00003"}]
        }
    ]
};

const projId = "00003";

// E.g Filter by project ID "00003"
const results = data.contacts.filter(x => x.projects.some(x => x.projId === projId));

console.log(JSON.stringify(results, null, 4));

答案 2 :(得分:0)

为此,lodash可能会过大。您可以使用.some(),它具有发现第一个匹配项时提早退出的额外好处:

app.get('/v1/projcontacts/:id', function(req, res) {
    var id = req.params.id;
    var projContacts = contactData.contacts.filter(contact => {
        return contact.projects.some(project => project.projId === id);
    });
    res.json(projContacts);
})