繁体   English   中英

使用 lodash 在数组中查找具有匹配键的对象

[英]Find object in array with a matching key using lodash

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

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

我想用 lodash 做类似的事情

lodash(myArray, 'uKey2')

并让它返回带有 uKey2 的对象

只需将_.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; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

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

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

您可以将键名传递给 _.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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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