Home > Back-end >  Assigning values to arrays with dynamic keys in nested objects in javascript
Assigning values to arrays with dynamic keys in nested objects in javascript

Time:09-18

I have problems understanding and creating dynamic keys of an object and assigning values to nested objects.

desired output:

{
SULS: {
  "Main Site": ["Home Page", "Login Page", "Register Page"],
  "Judge Site": ["Login Page", "Submittion Page"],
  "Digital Site": ["Login Page"],
},
Lamba: {
  CoreA: ["A23", "A24", "A25"],
  CoreB: ["B24"],
},
Indice: { 
  Session: ["Default Storage", "Default Security"] 
},

}

here is the input:

system([
  "SULS | Main Site | Home Page",
  "SULS | Main Site | Login Page",
  "SULS | Main Site | Register Page",
  "SULS | Judge Site | Login Page",
  "SULS | Judge Site | Submittion Page",
  "Lambda | CoreA | A23",
  "SULS | Digital Site | Login Page",
  "Lambda | CoreB | B24",
  "Lambda | CoreA | A24",
  "Lambda | CoreA | A25",
  "Lambda | CoreC | C4",
  "Indice | Session | Default Storage",
  "Indice | Session | Default Security",
]);

This is what i have been trying and keep getting errors while constructing the nested object:

function system(components) {
  let obj = components.reduce((mainObj, input) => {
    let [systemName, component, subComponent] = input.split(" | ");

    return {
      ...mainObj,
      [systemName]: {
        ...(mainObj[systemName] || {}),
        [component]: [...(mainObj[systemName][component] || []), subComponent],
      },
    };
  }, {});
  console.log(obj);
}

I have been stucked for a few days and appreciate if anyone can help

CodePudding user response:

Your code has the correct logic. There is just an error on this line:

    [component]: [...(mainObj[systemName][component] || []), subComponent],

...when mainObj[systemName] is still undefined.

This is easily solved with optional chainging:

    [component]: [...(mainObj[systemName]?.[component] || []), subComponent],
  • Related