简体   繁体   中英

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'

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

使用 ES6:

const updatedProducts = products.map(({text: label, value})=>({value, label}));
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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM