1

Given input:

let input = [
  {
    schema: ["user", "email"],
    value: "test@test.com"
  },
  {
    schema: ["user", "name", "firstName"],
    value: "John"
  },
];

let output = {};

for (let i = 0; i < input.length; i++) {
    let data = input[i];

    for (let j = 0; j < data.schema.length; j++) {
        let s = data.schema[j];
        // How to set nested levels here ? eg: output["user"]["email"] = {};
    }
}

Expected output:

{
    "user": {
        "email": "test@test.com",
        "name": { 
            "firstName": "John" 
        }
    }
}

Here "schema" represents the nested structure in JSON for the data.

What is the approach for dynamically setting nested attributes using Javascript ?

Eugene Mihaylin
  • 1,736
  • 3
  • 16
  • 31
Sudhir Shrestha
  • 1,106
  • 1
  • 12
  • 25

1 Answers1

2

You could use reduce to "deepen" the output object until the level where the property/value needs to be set:

const input = [{schema: ["user", "email"],value: "test@test.com"},{schema: ["user", "name", "firstName"],value: "John"},];
const output = {};

for (const obj of input) {
    obj.schema.slice(0, -1).reduce(
        (acc, lvl) => acc[lvl] || (acc[lvl] = {}), 
        output
    )[obj.schema.slice(-1)[0]] = obj.value;
}

console.log(output);

This way it also works if the schema array has more than 2 values.

trincot
  • 317,000
  • 35
  • 244
  • 286