This sounds like a simple task, but I can't quite figure it out: I have an array :
var array = ['opt1','sub1','subsub1','subsubsub1']
From that I want to generate the following objects:
{ opt1:{ sub1:{ subsub1:{ subsubsub1:{} } } } }
I have a way to do it, making a string and using eval, but I'm looking to avoid that, any idea?
const obj = { code: "AA", sub: { code: "BB", sub: { code: "CC", sub: { code: "DD", sub: { code: "EE", sub: {} } } } } }; Notice that for each unique couple in the string we have a new sub object and the code property at any level represents a specific couple. We can solve this problem using a recursive approach.
To update an object's property in an array of objects, use the map() method to iterate over the array. On each iteration, check if the current object is the one to be updated. If it is, modify the object and return the result, otherwise return the object as is. Copied!
You could use reduce
:
var array = ['opt1','sub1','subsub1','subsubsub1']; var object = {}; array.reduce(function(o, s) { return o[s] = {}; }, object); console.log(object);
But this was only introduced in ECMAScript 5.1, so it won't be supported in some older browsers. If you want something that will be supported by legacy browsers, you could use the polyfill technique described in the MDN article above, or a simple for
-loop, like this:
var array = ['opt1','sub1','subsub1','subsubsub1']; var object = {}, o = object; for(var i = 0; i < array.length; i++) { o = o[array[i]] = {}; } console.log(object);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With