我在项目中使用 Lodash JavaScript 库,但在获取父数组键对象过滤对象时遇到问题:
我有以下数据:
var data = {
5: [{
id: "3",
label: "Manish"
}, {
id: "6",
label: "Rahul"
}, {
id: "7",
label: "Vikash"
}],
8: [{
id: "16",
label: "Pankaj"
}, {
id: "45",
label: "Akash"
}],
9: [{
id: "15",
label: "Sunil"
}]
}
我的要求是,如果我有 [6,16]
数组,那么我想要一个包含值 5,8
的新结果数组,因为这两个数组键有包含 id:"6"和 id:"16"
我尝试使用 _.flatten 和 _.pick 方法但无法工作。我使用了以下代码;
var list = [];
_.each(data, function(item){
list.push(_.omit(item, 'id'));
list.push(_.flatten(_.pick(item, 'id')));
});
var result = _.flatten(list);
console.log(result);
最佳答案
var res = _([6, 16]).map(function(id){
return _.findKey(data, function(arr){
return _.some(arr, {id: new String(id)});
})
}).compact().uniq().value();
关于javascript - 使用 lodash 获取深层嵌套对象中的父数组键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35648838/