从数组构建assoc / indexed混合对象

时间:2015-06-22 21:48:10

标签: javascript arrays node.js nodes lodash

使用node和lodash,我有一个如下所示的数组:

[
    [ 'key10', 'key20', 'key30', 'value1' ],
    [ 'key10', 'key20', 'key31', 'value2' ],
    [ 'key10', 'key20', 'key32', 'valu3' ],
    [ 'key10', 'key20', 'key33', 'value4' ],
    [ 'key10', 'key20', 'key34', 'value5' ],
    [ 'key10', 'key20', 'key35', 'value6' ],
    [ 'key10', 'key20', 'key36', 'value7' ],
    [ 'key10', 'key20', 'key37', 'value8' ],
    [ 'key10', 'key20', 'key38', 'value9' ],
    [ 'key10', 'key20', 'key39', 'key50', 'value10' ],
    [ 'key10', 'key20', 'key39', 'key51', 'key60', 'value11' ],
    [ 'key10', 'key20', 'key39', 'key51', 'key61', 'value12' ],
    [ 'key10', 'key20', 'key39', 'key51', 'key60', 'value13' ],
    [ 'key10', 'key20', 'key39', 'key51', 'key61', 'value14' ],
    [ 'key10', 'key20', 'key39', 'key50', 'value15' ]
]

我正在尝试将其转换为:

{
    key10: {
        key20: {
            key30: 'value1',
            key31: 'value2',
            key32: 'value3',
            key33: 'value4',
            key34: 'value5',
            key35: 'value6',
            key36: 'value7',
            key37: 'value8',
            key38: 'value9',
            key39: [{
                key50: 'value10',
                key51: [{
                    key60: 'value11',
                    key61: 'value12'
                },{
                    key60: 'value13',
                    key61: 'value14'
                }]
            },{
                key50: 'value15',
                key51: []
            }]
        }
    }
}

请注意,我确实有一个库,用于定义有关每个键的信息,如下所示:

lib = {
    key10: {
        name: "some_random_name",
        .....
    }
    .......
}

我只使用了以下函数到目前为止,但是这个版本使用相同的密钥覆盖现有值,而不是将它们推送到数组。

function buildTagTree(obj, prop, value) {
    var aryLength = prop.length;
    var e = prop.shift();
    if (!lib[e]) {
        log('error', "Key %s not found in the library.", e);
    }else{
        var n = _.clone(lib[e].name);
        if (aryLength > 1) {
            obj[n] = Object.prototype.toString.call(obj[n]) === "[object Object]" ? obj[n] : {};
            buildTagTree(obj[n], prop, value);
        }else{
            obj[n] = value;
        }
    }
}

我正在通过运行这个来开始这个过程:

var tree = {}
buildTagTree(tree, _.dropRight(arr), _.last(arr));
console.log(tree);

0 个答案:

没有答案