[英]JavaScript or Lodash find objects by key
In an array of objects with diff keys, how do I find objects by key using ES6 or Lodash?在具有 diff 键的对象数组中,如何使用 ES6 或 Lodash 按键查找对象?
const arr = [{a:2}, {b:3}, {fred:10}]
I want the result to be:我希望结果是:
=> [{a:2}, {fred:10}]
I don't want to use an omit style approach.我不想使用省略风格的方法。
const filtered = arr.filter(obj => obj.hasOwnProperty("a") || obj.hasOwnProperty("fred"));
// or, if you have dynamic / lots of keys:
const keys = ["a", "fred"];
const filtered = arr.filter(obj => keys.some(key => obj.hasOwnProperty(key));
filter method will be useful.过滤方法会很有用。 Create a function and pass an array of
keys
.创建一个函数并传递一个
keys
数组。 Inside filter function check if the key is matching with the parameter array.内部过滤器函数检查键是否与参数数组匹配。 If it passed then return that object
如果它通过,则返回该对象
var orgObject = [{ a: 2 }, { b: 3 }, { fred: 10 }]; function searchByKey(keyNames) { return orgObject.filter(function(item) { for (var keys in item) { if (keyNames.indexOf(keys) !== -1) { return item } } }) } console.log(searchByKey(['a', 'fred']))
Basically you want all the objects from the array who have the fields a
or fred
.基本上,您需要数组中具有
a
或fred
字段a
所有对象。 You can use the hasOwnProperty()
on the objects while filtering.您可以在过滤时对对象使用
hasOwnProperty()
。
_.filter(array, elem => elem.hasOwnProperty('a') || elem.hasOwnProperty('fred'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.