Lodash _.flatMapDepth返回深度嵌套的对象数组

时间:2019-08-28 07:57:19

标签: javascript lodash

我试图从深层嵌套结构中获取一个数组,但我却能够获得一个层。即使我将深度设为4,我也无法获得。

感谢您的帮助

输入

let a = [{b: [{c: [{d: [{e: "name"}]}]}]}]

尝试片段

   let output = _.flatMapDepth(a, 'e', 3);

获取空数组

我需要使用lodash达到以下要求

output = [{e: "name"}]

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

最好使用_()。flatMap

 let a = [{b: [{c: [{d: [{e: "name"}]}]}]}];
console.log(a);
let output1 = _(a).flatMap('b').flatMap('c').flatMap('d').value();
console.log(output1); // [ { e: 'name' } ]
let output2 = _(a).flatMap('b').flatMap('c').flatMap('d').flatMap('e').value();
console.log(output2); // [ 'name' ]

这一遍历嵌套对象并解析它们!

答案 1 :(得分:-1)

来自Lodash docs

_.flatMapDepth

// _.flatMapDepth(collection, [iteratee=_.identity], [depth=1])

function duplicate(n) {
  return [[[n, n]]];
}

_.flatMapDepth([1, 2], duplicate, 2);
// => [[1, 1], [2, 2]]

_.identity

// _.identity(value)

var object = { 'a': 1 };

console.log(_.identity(object) === object);
// => true

我认为这应该有所帮助。


如果这没有帮助。我已经为您的问题编写了JavaScript解决方案:

let a = [{
    b: [{
        c: [{
            d: [{
                e: "name"
            }]
        }]
    }]
}, {
    b: [{
        c: [{
            d: [{
                e: "age"
            }]
        }]
    }]
}];

function getDeepKeys(arr, key, maxDepth = 8) {
    let res = [];
    let depth = 0;
    for (let i = 0; i < arr.length; i++) {
        const obj = arr[i];
        if (typeof obj !== "object" || obj == null) {
            continue;
        }
        for (const k in obj) {
            if (obj.hasOwnProperty(k)) {
                const element = obj[k];
                if (k === key) {
                    res.push(obj);
                    // can also be res.push(element)
                    // if you want the contents of obj to be added to the resulting array
                    continue;
                } else if (depth <= maxDepth) {
                    res = getDeepKeys(element, key).concat(res);
                    depth++;
                }
            }
        }
    }
    return res;
}

let keys = getDeepKeys(a, "e");
console.log(keys);

但是要小心。如果存在没有e键的对象,则会出现无限循环错误。因此,我创建了depthmaxDepth变量。您可以像这样调整此值:getDeepKeys(a, "e", 12);(现在maxDepth等于12,而不是默认值10)。