I have a dynamic array for examples:
var myarray = ['country','state','city','town'] or
var myarray = ['country','state'] or
var myarray = ['country','state','city']
How to convert it to
var myobject = country['state']['city']['town'] or
var myobject = country['state'] or
var myobject = country['state']['city']
because finally I will assign a value to the object for example country['state']['city']['town'] = 'some small town in Italy' etc
Thanks in advance
CodePudding user response:
A little bit of recursion will take care of that for you:
const array = ['country','state','city','town'];
const fn = ([first, ...rest]) => ({ [first]: rest.length ? fn(rest) : null });
console.log(fn(array));
CodePudding user response:
You may use Array.reduceRight() to create such an object:
var myarray = ['country','state','city','town'];
const obj = myarray.reduceRight((acc, cur) => ({ [cur]: acc }), 'some small town in Italy');
console.log(obj);
