简体   繁体   中英

Finding nested object in a collection with Lodash

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.

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); 

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM