1

Given input:

let input = [
  {
    schema: ["user", "email"],
    value: "[email protected]"
  },
  {
    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": "[email protected]",
        "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 ?

4
  • What is data.schema? What about output["user"]["email"] = {}; isn’t working? Commented Feb 18, 2018 at 11:58
  • @Xufox : I cannot use output["user"]["email"] since "user" and "email" will be dynamic. Commented Feb 18, 2018 at 12:00
  • Okay, then just replace "user" and "email" with the variables containing the dynamic strings. See Using a variable for a key in a JavaScript object literal. Commented Feb 18, 2018 at 12:07
  • It is represented as array eg: ["user", "email"] so I will need to loop to set it. Please refer to the example, I have updated it. Commented Feb 18, 2018 at 12:11

1 Answer 1

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: "[email protected]"},{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.

Sign up to request clarification or add additional context in comments.

3 Comments

The OP has changed the question's body!
Thanks for letting me know. Adapted the input in my answer accordingly.
Works flawlessly, Thank you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.