0

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

1
  • 1
    Try payload.map(elm => { return {[elm.id]: elm.balance } }) Commented Aug 31, 2021 at 15:45

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.