2021-10-30

Create array of objects from sorting another array of objects

I want to create an array of objects, and the first elements from the each data object to be a separate object, the second element from the each data object to be another separate object and so on...

let array = [{   
    data: {
       center1: "1",
       storage1: "1",
       system1: "1",
    }
  },
  {  
    data: {
       center2: "2",
       storage2: "2",
       system2: "2",
    }
  }
]

Expected result:

[
    { center1: "1",  center2: "2"},
    { storage1: "1",  storage2: "2"},
    { system1: "1",  system2: "2"}
]

And this is what I tried do to but is not working really well:)

 const rows = [];
 array.forEach((item, index) => {
      for (let key in item.data) {
          rows.push({index : key + ': ' + item.data[key]});
      }
 });

The output is this:

[
    {index : 'center1: 1'},
    {index : 'storage1: 1'},
    {index : 'system1: 1'},
    {index : 'center2: 2'},
    {index : 'storage2: 2'},
    {index : 'system2: 2'}
]

Thank you for your help!



from Recent Questions - Stack Overflow https://ift.tt/3BnlwUZ
https://ift.tt/eA8V8J

No comments:

Post a Comment