Generated recursive array based object
I have an array, which is a list of keys: ['one', 'two', 'three']
.
I need to generate an object of the following format:
{
path: 'one',
nested: {
path: 'two',
nested: {
path: 'three'
}
}
}
I have tried several approaches so far, but they seem to be quite messy (I have one method that uses while(current = array.pop())
, but it takes multiple conditionals to handle the first and last items.
Is there a neater recursive strategy?
source to share
You can use the method reduce()
and as an accumulator skip object to which you want to add properties.
var arr = ['one', 'two', 'three']
var obj = {}
arr.reduce(function(r, e, i) {
r.path = e;
return arr[i+1] ? r.nested = {} : r
}, obj)
console.log(obj)
If you only want to use recursion without a loop, you can create a function like this.
var data = ['one', 'two', 'three']
var obj = {}
function makeObj(arr, n, o) {
if (n == arr.length - 1) o.path = arr[n]
else {
o.path = arr[n];
o.nested = {}
makeObj(arr, n += 1, o.nested)
}
return o.nested
}
makeObj(data, 0, obj)
console.log(obj)
source to share
var arr = ['one', 'two', 'three'];
var tree = arr.reduceRight((nested, path) => {
return nested? {path, nested}: {path};
}, null);
console.log(tree);
or even better / simpler, just:
var arr = ['one', 'two', 'three'];
var tree = arr.reduceRight((nested, path) => ({path, nested}), null);
console.log(tree);
This simplifies things for the JS engine if all objects have the same hidden class (simplified: same property names).
source to share
To solve this problem, you can use a decrement for
:
var props = ['one','two','three'],
obj;
for(var a = props.length;a--;) {
var temp = { path: props[a] };
if(obj) {
temp.nested = obj;
}
obj = temp;
}
console.log(obj);
source to share