Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change array key name in react native

I am api response I am getting below array as a response . I have to change the inside key name of array and then send to ui . Please help . I got connfused .

"callDetails": [
        {
          "quantity":5,
           "msisdn":1,
          "otherMSISDN": 2348032002207
        },
        {
          "quantity": 5,
          "msisdn": 2347062021398,
          "otherMSISDN": 2347038834140
        },
        {
          "quantity": 4,
          "msisdn": 2347062021398,
          "otherMSISDN": 2348166692364
        },
        ]

// I have to convert my array from above array to below array .

"callDetails": [
        {
          "frquency":5,
           "totalRows":1,
          "frequentNumber": 2348032002207
        },
        {
          "frquency": 5,
          "totalRows": 1,
          "frequentNumber": 2347038834140
        },
        {
          "frquency": 4,
          "totalRows": 1,
          "frequentNumber": 2348166692364
        },
        ]
like image 255
Abhigyan Gaurav Avatar asked Apr 09 '26 11:04

Abhigyan Gaurav


2 Answers

You can use Array.map() to achieve this, something like this may do:

const response = {

"callDetails": [
        {
          "quantity":5,
           "msisdn":1,
          "otherMSISDN": 2348032002207
        },
        {
          "quantity": 5,
          "msisdn": 2347062021398,
          "otherMSISDN": 2347038834140
        },
        {
          "quantity": 4,
          "msisdn": 2347062021398,
          "otherMSISDN": 2348166692364
        }
        ]

}

response.callDetails = response.callDetails.map(({quantity, msisdn, otherMSISDN}) => {
  return {
    frquency: quantity,
    totalRows: msisdn,
    frequentNumber: otherMSISDN
  }
});

console.log(response)
like image 161
Ashish Ranjan Avatar answered Apr 10 '26 23:04

Ashish Ranjan


Above all answers are identical. I am just adding up something. If you want to use the same variable and do not want to allocate memory to new variable, then you can do like this:

var callDetails = [{
    "quantity": 5,
    "msisdn": 1,
    "otherMSISDN": 2348032002207
  },
  {
    "quantity": 5,
    "msisdn": 2347062021398,
    "otherMSISDN": 2347038834140
  },
  {
    "quantity": 4,
    "msisdn": 2347062021398,
    "otherMSISDN": 2348166692364
  }
];

for (const detail of callDetails) {
    detail['frquency']= detail.quantity;
    detail['totalRows']= detail.msisdn;
    detail['frequentNumber']= detail.otherMSISDN;
    delete detail.quantity, delete detail.msisdn, delete detail.otherMSISDN;
}

console.table(callDetails);
like image 30
Varun Sharma Avatar answered Apr 10 '26 23:04

Varun Sharma