Srinu
Srinu

Reputation: 151

How to rename key of object in an array

How to replace array element value with another

i have array like this, without using jquery

 this.products = [
      { 
        text: 'prod1', 
        value: 1 
      },
      { 
        text: 'prod2', 
        value: 2 
      },
      { 
        text: 'prod3', 
        value: 3 
      }
 ];

i want to replace 'text' to 'label'

Upvotes: 9

Views: 13373

Answers (4)

NickC
NickC

Reputation: 377

For people like me who are looking for an answer that does not mutate the original objects (which will cause errors in React) but instead want to return a new array full of new objects with only one specific key renamed in each object I have create the following function.

export const renameKey = (arr, oldKey, newKey) => {
  let newArray = [];

  arr.forEach((obj) => {
    let newObj = {};
    const keys = Object.keys(obj);
    keys.forEach((key) => {
      if (key === oldKey) {
        Object.assign(newObj,{ [newKey]: obj[oldKey] });
      } else {
        Object.assign(newObj,{ [key]: obj[key] });
      }
    });
    newArray.push(newObj);
  });

  return newArray;
};

Upvotes: 0

Ronak Sethi
Ronak Sethi

Reputation: 111

There are many ways using map in ES6

    var products = [
          { 
            text: 'prod1', 
            value: 1 
          },
          { 
            text: 'prod2', 
            value: 2 
          },
          { 
            text: 'prod3', 
            value: 3 
          }
     ];

    const newProducts = products.map(({text: label, value})=>({value, label}));
    console.log(newProducts );

    console.log("===================Another  Method====================")


    products.map((el)=>{
    el.label = el.text
    delete el.text
    })

    console.log(products);

Upvotes: 3

Gnun Ulikhanyan
Gnun Ulikhanyan

Reputation: 151

using ES6:

const updatedProducts = products.map(({text: label, value})=>({value, label}));

Upvotes: 12

Sankar
Sankar

Reputation: 7107

How about this?

var products = [{
    text: 'prod1',
    value: 1
  },
  {
    text: 'prod2',
    value: 2
  }, {
    text: 'prod3',
    value: 3
  }
];

products.forEach(function(obj) {
  obj.label = obj.text;
  delete obj.text;
});
console.log(products);

Upvotes: 13

Related Questions