I need help converting several arrays:
x = ['a', 'b', 'c']
y = ['d', 'e', 'f']
z = ['d', 'g', 'h']
Into a single JSON:
{
a: { b: { c: 'done' }},
d: { e: { f: 'done' },
g: { h: 'done' }}
}
Is this possible using recursion? I can't seem to get it working properly so I was wondering if there is already an easy way to do this in 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"));
Output:
{
"a": {
"b": {
"c": "done"
}
},
"d": {
"e": {
"f": "done"
},
"g": {
"h": "done"
}
}
}
Note: this script will fail if your input is like:
var paths = [
['a', 'b', 'c'],
['a', 'b', 'c', 'd' ]
];
It decided c
should be "done"
but then there is another level. maybe this wont ever happen, if it does, figure out what you want the result to be.
A version with Array#forEach()
and 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>');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.