Convert list of Objects when the levels are given

2020-04-27 09:37发布

问题:

Suppose I have an array which tells me the list of labels and a value that I need to add them into a JSON object. How do you transform it so?

So basically I have is an array and a value 100

arr = ["1", "Male"]

Should be transform it into a object as so.

obj = {
    "1":{
        "Male":100
        }
    }

回答1:

You could use reduceRight for this. Use value as the initialValue of reduce and create a new level of nesting in every loop.

function createObj(paths, value) { 
  return paths.reduceRight((r, key) =>  ({ [key] : r }), value)  
}

console.log(createObj(["1", "Male"], 100))
console.log(createObj(["level 1", "level 2", "level 3" ], "value"))



回答2:

You could save the last property and reduce the object. At the end assign the value to the last property.

This solution respects already given properties.

function setValue(object, path, value) {
   var last = path.pop();
   path.reduce((o, k) => o[k] = o[k] || {}, object)[last] = value;
}

var object = {};

setValue(object, ["1", "Male"], 100);
console.log(object);

setValue(object, ["1", "Female"], 200);
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }