繁体   English   中英

将多个数组转换为单个JSON

[英]Convert multiple arrays to single JSON

我需要转换几个数组的帮助:

x = ['a', 'b', 'c']
y = ['d', 'e', 'f']
z = ['d', 'g', 'h']

转换成单个JSON:

{
    a: { b: { c: 'done' }},
    d: { e: { f: 'done' },
         g: { h: 'done' }}
}

使用递归可以吗? 我似乎无法使其正常工作,所以我想知道JS中是否已经有一种简单的方法来做到这一点。

var struct = {};
var paths = [
    ['a', 'b', 'c'],
    ['d', 'e', 'f'],
    ['d', 'g', 'h']
];

paths.forEach(function (path) {
    var ref;
    ref = struct;
    path.forEach(function (elem, index) {
        if (!ref[elem]) {
            ref[elem] = index === path.length - 1 ? "done": {};
        }
        ref = ref[elem];
    });
});
console.log(JSON.stringify(struct, null, "\t"));

输出:

{
    "a": {
        "b": {
            "c": "done"
        }
    },
    "d": {
        "e": {
            "f": "done"
        },
        "g": {
            "h": "done"
        }
    }
}

注意:如果您输入以下内容,此脚本将失败:

var paths = [
    ['a', 'b', 'c'],
    ['a', 'b', 'c', 'd' ]
];

它决定c应该"done"但是还有另一个层次。 也许这永远不会发生,如果发生的话,弄清楚您想要的结果是什么。

具有Array#forEach()Array#reduce()

 var x = ['a', 'b', 'c'], y = ['d', 'e', 'f'], z = ['d', 'g', 'h'], object = function (array) { var o = {}; array.forEach(function (a) { var last = a.pop(); a.reduce(function (r, b) { r[b] = r[b] || {}; return r[b]; }, o)[last] = 'done'; }); return o; }([x, y, z]); document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>'); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM