Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

creating an multidimensional Object dynamically from an multidimensional array

Im trying to create an multidimensional Object like this one:

{ A : {a1: {},a2:{}}, B: {b1:{},b2:{}}}

from an multidimensional array like this one:

let array1 = [
      ['A', 'a1'],
      ['A', 'a1'],
      ['A', 'a2'],
      ['B', 'b1'],
      ['B', 'b1'],
      ['B', 'b2'],
    ];

I’m trying this for some hours now and was also reading plenty of entrys here on stackoverflow, but nothing really fits this specific case.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What i did so far:

    let array1 = [
      ['A', 'a1'],
      ['A', 'a1'],
      ['A', 'a2'],
      ['B', 'b1'],
      ['B', 'b1'],
      ['B', 'b2'],
    ];

    let object1 = {};

    array1.forEach(function (subArray) {
      let level1 = subArray[0];
      let level2 = subArray[1];

      object1[[level1]] = { ...{ [level2]: {} } };
    });

    console.log('object: ', object1);
    //desired output:  object = { A : {a1: {},a2:{}}, B: {b1:{},b2:{}}}
    //what I get:  object = { A : {a2:{}}, B: {b2:{}}}

So somehow in my code the entrys like {a1: {}} are getting overwritten in each iteration instead of adding a new entry.

Thanks a lot in advance.

>Solution :

Keep previous properties using ...object1[[level1]]:

    let array1 = [
      ['A', 'a1'],
      ['A', 'a1'],
      ['A', 'a2'],
      ['B', 'b1'],
      ['B', 'b1'],
      ['B', 'b2'],
    ];

    let object1 = {};

    array1.forEach(function (subArray) {
      let level1 = subArray[0];
      let level2 = subArray[1];

      object1[[level1]] = {
        ...object1[[level1]], // Keep previous properties
        ...{ [level2]: {} } // Add new
      };
    });

    console.log('object: ', object1);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading