How to push an array of object as key value pair into an array

Lets say I am getting a JSON from an API like this

lineItem = {
  "rows": {
    "10010": [
      {
        "id": "[10010,1,1]",
        "po_item": 10010,
        "schedule_no": 1,
        "chainage_no": 1
      },
      {
        "id": "[10010,2,1]",
        "po_item": 10010,
        "schedule_no": 2,
        "chainage_no": 1
      }
    ],
    "10020": [
      {
        "id": "[10020,1,1]",
        "po_item": 10020,
        "schedule_no": 1,
        "chainage_no": 1
      },
      {
        "id": "[10020,2,1]",
        "po_item": 10020,
        "schedule_no": 2,
        "chainage_no": 1
      }
    ]
  }
}

I need to populate an array like below,

resultArray = [
  "10010": [
      {
          "id": "[10010,1,1]",
          "status": 0
      },
      {
          "id": "[10010,2,1]",
          "status": 0
      }
  ],
  "10020": [
      {
          "id": "[10020,1,1]",
          "status": 0
      },
      {
          "id": "[10020,2,1]",
          "status": 0
      }
  ]
]

I have tried with the following method

Object.keys(this.lineItem.rows).map(key => {
  this.resultArray[key] = [];

  this.lineItem.rows[key].map(item => {
    this.resultArray[key].push({ id: item.id, status: 0 });
  });
  
});

But I am getting result like below with empty elements

(10021) [empty × 10010, Array(2), empty × 9, Array(2)]
10010: (2) [{…}, {…}]
10020: (2) [{…}, {…}]
length: 10021
__proto__: Array(0)

here you can see empty x 10010 and empty x 9. when I try to send the resultArray as a payload to an API it is adding 10019 null and then two arrays.

104 thoughts on “How to push an array of object as key value pair into an array”

Leave a Comment