javascript - 使用 Lodash 查找集合中的嵌套对象

标签 javascript arrays hash lodash es5-compatiblity

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

使用 _.find(collection, { 'uuid': '349' }) 将返回 undefined。

如何查找具有uuid == 349的哈希值?

查找的预期返回为:{ 'uuid': '349', 'd': 'd' }

必须使用 ES5 标准编写,并且必须使用 Lodash。

最佳答案

使用纯 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);

关于javascript - 使用 Lodash 查找集合中的嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57669969/

相关文章:

ruby - hash值与 `<<`算子的交互

perl - 如何引用 Perl 中的特定哈希值?

javascript - node.js 需要 memcached 是什么?

javascript - 包含数组的对象 - 是否有更简单的方法来编写这种常见模式

java - 将带有数组参数的方法传递给驱动程序/测试文件?

php - MySQL/PHP 自然排序

python - 是否可以通过 django 管理面板动态添加新字段

javascript - Canvas - 有时使用 lineTo() 的笔画会产生边缘

javascript - Wp 媒体库元框无法读取未定义的属性 'state'

javascript - 发布 [object%20HTMLInputElement] 404 在 $.ajax 提交上找不到