OjayChima
OjayChima

Reputation: 97

How can a create another array from my javascript array

I'm working with an array from an api call, which I would like to rearrange for something else.

payload = [
           {
            "id": rexiy,
            "orderLabel": "PREP",
            "balance": 1900,
            "virtual": false,
            "type": "credit",
           },
           {
            "id": erptq,
            "orderLabel": "PREP",
            "balance": 500,
            "virtual": true,
            "type": "debit"
            }
           ]

I'm trying to create a new array that would have this format

array = [
         {
          rexiy:1900
         },
         {
          erptq:500
         } 
        ]

How do I go about it

Upvotes: 0

Views: 35

Answers (1)

Jamiec
Jamiec

Reputation: 136114

You can use object destructuring and map to do this:

const payload = [{
    "id": "rexiy",
    "orderLabel": "PREP",
    "balance": 1900,
    "virtual": false,
    "type": "credit",
  },
  {
    "id": "erptq",
    "orderLabel": "PREP",
    "balance": 500,
    "virtual": true,
    "type": "debit"
  }
]

const result = payload.map(({id, balance}) => ({
  [id]: balance
}));

console.log(result);

Upvotes: 1

Related Questions