Given is an array like this:
var level = ["a", "b", "x"];
The output should be:
{
"a": {
"b": {
"x": {
}
}
}
}
I tried this:
var level = ["a", "b", "x"];
var o = {};
for (var c = 0, len = level.length; c < len; c +=1 ) {
var part = level[c];
o[part] = {}; // how to remember the last part?
}
How can I remember the last part and add the next level?
You can use reduceRight method by passing an arrow
function as argument .
var level = ["a", "b", "x"]; let result = level.reduceRight((obj, elem) => ({[elem]: obj}), {}); console.log(result);
Simplest tweak would be to reassign o
on each iteration:
var level = ["a", "b", "x"]; var o = {}; var initialO = o; for (var c = 0, len = level.length; c < len; c +=1 ) { var part = level[c]; o[part] = {}; o = o[part]; } console.log(initialO);
This might be a clearer way of doing it, though:
const level = ["a", "b", "x"]; const result = {}; level.reduce((accum, key) => { accum[key] = {}; return accum[key]; }, result); console.log(result);
You might use a check if the level exist and assign only an object if not set.
function addLevels(levels, object) { levels.reduce((o, l) => o[l] = o[l] || {}, object); } var object = {}; addLevels(["a", "b", "x"], object); addLevels(["a", "d", "z"], object); console.log(object);
This one, I think is easiest if you write it in a functional style.
var level = ["a", "b", "x"];
var o = {};
level.reduce(function (obj, key) {
o[key] = {};
return o[key];
}, o);
Or with a recursive function
const level = ["a", "b", "x"]; const f = (i) => i === level.length ? {} : {[level[i]]: f(i+1)}; console.log(f(0));
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.