查询带有随机名称的嵌套对象 - lodash/javaScript



需要获取找到匹配孩子的对象的父母。

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的sud be

{
 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; }

最新更新