【问题标题】:Find object in array with a matching key using lodash使用 lodash 在数组中查找具有匹配键的对象
【发布时间】:2020-02-07 18:57:42
【问题描述】:

我有一个对象数组,每个对象都有一个唯一的键。 示例:

const myArray = [
{uKey1: 'hey', otherValue: 1},
{uKey2: 'hey', otherValue: 1},
{uKey3: 'hey', otherValue: 1}
];

我想用 lodash 做类似的事情

lodash(myArray, 'uKey2')

并让它返回带有 uKey2 的对象

【问题讨论】:

  • 不是lodash,但你可以看看Array.prototype.find()也许:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • 不完全相关,但我不明白 lodash 的用例是什么。有人可以向我解释吗?是为了兼容旧浏览器还是什么?
  • @Klaycon 有点。 lodash 提供的许多功能已经被引入到适当的语言中。但是,仍然有一些功能没有。
  • @zero298 这是有道理的,但我对许多类似问题的下意识反应是“你不需要 lodash,javascript 数组助手已经这样做了”——我想这还不够出于某种原因。

标签: javascript lodash


【解决方案1】:

您可以在第二个参数上将键名传递给 _.find:

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
<script>
  const myArray = [{
      uKey1: 'hey',
      otherValue: 1
    },
    {
      uKey2: 'hey',
      otherValue: 1
    },
    {
      uKey3: 'hey',
      otherValue: 1
    }
  ];

  console.log(_.find(myArray, 'uKey1'))
  console.log(_.find(myArray, 'uKey2'))
  console.log(_.find(myArray, 'uKey3'))
</script>

【讨论】:

    【解决方案2】:

    只需将_.find_.has 结合起来即可。

    您甚至可以创建一个 mixin(又名插件),如下所示。

    纯JS版本还不错。

    _.mixin({
      findObjectByPresentKey : function(arr, key) {
        return _.find(arr, function(obj) {
          return _.has(obj, key);
        })
      }
    });
    
    const myArray = [
      { uKey1: 'hey', otherValue: 1 },
      { uKey2: 'hey', otherValue: 1 },
      { uKey3: 'hey', otherValue: 1 }
    ]
    
    // In-line
    console.log(_.find(myArray, 'uKey3'))
    
    // As a plugin
    console.log(_.findObjectByPresentKey(myArray, 'uKey3'))
    
    // Pure JS (Edge)
    console.log(myArray.find(obj => obj.hasOwnProperty('uKey3')));
    
    // IE 9+
    console.log(myArray.filter(obj => obj.hasOwnProperty('uKey3')).pop());
    .as-console-wrapper { top: 0; max-height: 100% !important; }
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"&gt;&lt;/script&gt;

    请参考:_.find(collection, [predicate=_.identity], [fromIndex=0])

    // The `_.property` iteratee shorthand.
    _.find(users, 'active');
    // => object for 'barney'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-16
      • 1970-01-01
      相关资源
      最近更新 更多