简体   繁体   中英

Populate nested object from array?

I have a question, how to create nested object from array? Ie I have a following array:

var myArr = ['foo', 'bar', 'baz'] and need to make it an object like:

myObj = {foo: { bar: { baz: { } } }}

How can I do that properly?

Use reduce()

 var myArr = ['foo', 'bar', 'baz']; var myObj = {}; myArr.reduce(function(a, b) { a[b] = {}; return a[b]; }, myObj); console.log(myObj);

you can do better ! :

 let arr = ['foo', 'bar', 'baz']; let obj = arr.reduceRight((a,c)=>({[c]:a}),{}) document.write( JSON.stringify(obj) )

Using .reduceRight() method

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.

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