需要获取找到匹配子对象的对象的父对象..
Obj =
{
trees:{
small:[1,2,3],
medium:[4,5,13],
large:[1,2,10]
},
plants:{
small1:[11,12,3],
medium1:[14,15,3],
large1:[11,12,10]
}
}
查询 3 的预期结果为
{
trees:{
small:[1,2,3]
},
plants:{
small1:[11,12,3],
medium1:[14,15,3]
}
}
所以我尝试的是
function findInObjectsOfObjects(obj) {
console.log(obj)
for (var i in obj) {
console.log(obj[i])
if (typeof(obj[i]) == "object" && obj[i].length < 1)
findInObjectsOfObjects(obj[i])
else {
return obj[i]; -- but loop breaks here
}
}
}
我试图匹配值
for (var obj1 in obj) {
findInObjectsOfObjects(obj1).indexOf(3) // instead will be using indexOf
}
但它只返回第一个数组并在返回时中断。问题是它可以在巢穴的任何深处。
最佳答案
您可以通过检查内部对象的值和级联返回来采用迭代和递归方法。
function find(object, value) {
var result;
Object.keys(object).forEach(function (k) {
var found;
if (Array.isArray(object[k]) && object[k].indexOf(value) !== -1) {
result = result || {};
result[k] = object[k];
return;
}
if (object[k] && typeof object[k] === 'object') {
found = find(object[k], value);
if (found) {
result = result || {};
result[k] = found;
}
}
});
return result;
}
var object = { trees: { small: [1, 2, 3], medium: [4, 5, 13], large: [1, 2, 10] }, plants: { small1: [11, 12, 3], medium1: [14, 15, 3], large1: [11, 12, 10] } },
result = find(object, 3);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 查询具有随机名称的嵌套对象 - lodash/javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47619870/