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

Destructure an array of objects and create a new array with array keys as a new value in JavaScript

Distructure and array of object and create a new array of object with a new value from the array keys in Javascript.

Existing Array of object is this –

  [
    {
      "Semester One" : [
        {
          id:"1",
          name:"Name1",
        },
        {
          id:"2",
          name:"Name2",
        }
      ],
      "Semester Two" : [
        {
          id:"3",
          name:"Name3",
        },
        {
          id:"4",
          name:"Name4",
        }
      ]
    }
  ]

what I want to achive, is this :

[
  {
    id:"1",
    name:"Name1",
    semester:"Semester One" // array key
  },
  {
    id:"2",
    name:"Name2",
    semester:"Semester One" // array key
  },
  {
    id:"3",
    name:"Name3",
    semester:"Semester Two" // array key
  },
  {
    id:"4",
    name:"Name4",
    semester:"Semester Two" // array key
  },
]

I am able to successfully create an array of objects with a value, but I can’t access the array keys like "Semester One, Semester Two"

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

Here is what I have done so far –

 const arrObj = [];
    paperList.forEach((element) => {
      for (const key in element) {
        element[key].forEach((e, i) => {
          arrObj.push({
            ...e,
            semester: "", // don't know how to get this value
            isChecked: "",
          });
        });
      }
    });
    console.log(arrObj);

>Solution :

you can achieve the array like this, use a foreach and push to new array.


var newArray = [];

originalArray.forEach((item) => {
  Object.keys(item).forEach((key) => {
    item[key].forEach((obj) => {
      newArray.push({
        id: obj.id,
        name: obj.name,
        semester: key,
      });
    });
  });
});
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