Finding nested object in a collection with Lodash

321 Views Asked by At
var collection = {
  'key1': [
    { 'uuid': '123', 'a': 'a' },
    { 'uuid': '456', 'b': 'b',
      'randomKeyValue': [
        { 'uuid': '349', 'd': 'd' }
      ]
    }
  ],
  'key2': [
    { 'uuid': '890', 'c': 'c' }
  ]
}

Using _.find(collection, { 'uuid': '349' }) will return undefined.

How to find the hash that has uuid == 349?

The expected return of the find is: { 'uuid': '349', 'd': 'd' }

Must be written with ES5 standards and must use Lodash.

2

There are 2 best solutions below

2
On

It's fairly straightforward using plain js

var collection = {
    'key1': [
        { 'uuid': '123', 'a': 'a' },
        { 'uuid': '456', 'b': 'b' }
    ],
    'key2': [
        { 'uuid': '890', 'c': 'c' },
        { 'uuid': '349', 'd': 'd' }
    ]
}

const res = Object.values(collection).flat().find(({uuid}) => uuid === '349');
console.log(res);

2
On
_.filter(_.flatMap(collection), function(o) { return o.uuid == '349' });