使用lodash

时间:2016-02-01 18:33:00

标签: javascript lodash

我有深层嵌套对象的数组。我想编写一个函数来从这些数组中提取任意子对象。在某些情况下,嵌套属性的值是值和对象,在其他情况下,它们是数组。

数组示例如下:

[{parent: {level1: {level2: 'data'}}}]

[{parent: {level1: [{level2: {...}}, {level2: {...}}, {level2: {...}}]}}]

[{parent: {level1: [{level2: {level3: 'data'}}, {level2: {..}}, {level2: {..}}]}}]

在这样的数组上调用提取函数应该会产生一系列我们感兴趣的对象。

为上面的示例数组调用函数及其结果的示例:

extractChildren(source, 'level2') = [{level2: 'data'}]

extractChildren(source, 'level2') = [{level2: {...}, level2: {...}, level2: {...}]

extractChildren(source, 'level3') = [{level3: 'data'}]

是否有一种简洁的方法可以使用lodash实现此目的,或者我应该使用常规JavaScript来遍历属性?

P.S。可以认为它等同于XPath select all nodes with the name "nodename"

2 个答案:

答案 0 :(得分:1)

我希望,这有帮助:

'use strict';

let _ = require("lodash");
let source = [{parent: {level1: [{level2: {level3: 'data'}}, {level2: {}}, {level2: {}}]}}];

function extractChildren(source, specKey) {
    let results = [];
    let search = function(source, specKey) {
        _.forEach(source, function(item) {
            if (!!item[specKey]) {
                let obj = {};
                obj[specKey] = item[specKey];
                results.push(obj);
                return;
            }

            search(item, specKey);
        });
    };

    search(source, specKey);
    return results;
};

console.log(extractChildren(source, 'level3'));
// [ { level3: 'data' } ]

答案 1 :(得分:1)

来自this question

优雅:

function find_obj_by_name(obj, key) {
    if( !(obj instanceof Array) ) return [];

    if (key in obj)
        return [obj[key]];

    return _.flatten(_.map(obj, function(v) {
        return typeof v == "object" ? find_obj_by_name(v, key) : [];
    }), true);
}

高效:

function find_obj_by_name(obj, key) {
    if( !(obj instanceof Array) ) return [];

    if (key in obj)
        return [obj[key]];

    var res = [];
    _.forEach(obj, function(v) {
        if (typeof v == "object" && (v = find_obj_by_name(v, key)).length)
            res.push.apply(res, v);
    });
    return res;
}