Search code examples
javascriptlodash

Use Lodash to find objects in an array matches an id (complex, drilldown)


I have a set of id's.

let ids = ["5ae03c56dc0e82410d2746d7", "5ae05bf146e0fbeeb1869d7b", "5ae03c56dc0e82fd2f2746d6", "5ae04788c9e77cb0a03b3228", "5adefec246e0fb1c23f5ba6b", "5ae8498edc0e82c7cbad5026", "5ae84b4fc9e77c5db6fbf3f8"]

I also have a set of data that looks like the following.

{  
    "interactions":[  
        {  
            "author":{  
                "id":"10158567383880542",
                "name":"Stephen Wilson"
            },
            "meta":{  
                "tags":[  
                    {  
                        "id":"5ae04788c9e77cb0a03b3228"
                    },
                    {  
                        "id":"5ae04788c9e77cb0a03b365"
                    }
                ]
            }
        }
    ]
}

Inside the interactions array there are multiple objects. There is a property called "meta", inside the meta there is a property of type array called "tags".

I want to match the ids array to find and return any interactions where meta.tags.id is equal to any of the ids.

 let matches = _(interactions)
            .keyBy('meta.tags.id')
            .at(ids)
            .value();

The problem with the attempt here is that meta.tags is an array.


Solution

  • You can combine Array.prototype.filter(), Array.prototype.some() and Array.prototype.includes()

    Code:

    const ids = ["5ae05bf146e0fbeeb1869d7b", "5ae03c56dc0e82fd2f2746d6"]
    const data = {"interactions":[{"author":{"id":"10158567383880542","name":"Stephen Wilson"},"meta":{"tags":[{"id":"5ae04788c9e77cb0a03b3228"},{"id":"5ae04788c9e77cb0a03b365"}]}},{"author":{"id":"10158567383880543","name":"Phil Murray"},"meta":{"tags":[{"id":"5ae05bf146e0fbeeb1869d7b"},{"id":"5ae04788c9e77cb0a03b369"}]}},{"author":{"id":"10158567383880543","name":"Steve Jobs"},"meta":{"tags":[{"id":"5ae84b4fc9e77c5db6fbf3f8"},{"id":"5ae04788c9e77cb0a44469"}]}},{"author":{"id":"10158567383880543","name":"John Connor"},"meta":{"tags":[{"id":"5ae84b4fc9e778c5db6fbf3f8"},{"id":"5ae04788c94577cb0a44469"}]}}]};
    
    const result = data.interactions.filter(i => i.meta.tags.some(t => ids.includes(t.id)));
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }