skip to Main Content

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"

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);

2

Answers


  1. 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,
          });
        });
      });
    });
    
    Login or Signup to reply.
  2. Another solution you can use (shorter) :

    const arr = [
      {
          "Semester One" : [
            {
              id:"1",
              name:"Name1",
            },
            {
              id:"2",
              name:"Name2",
            }
          ],
          "Semester Two" : [
            {
              id:"3",
              name:"Name3",
            },
            {
              id:"4",
              name:"Name4",
            }
          ]
        }
      ];
    
    const result = arr.flatMap(sem =>                           // iterate through each elements
        Object.keys(sem).flatMap(semId =>                   // get semesters identifier
            sem[semId].map(y =>                             // map on semesters
                ({id: y.id, name: y.name, semester: semId}) // format the output
            )
        )
    );
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search