3

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'

SALEH
  • 1,472
  • 1
  • 12
  • 22
Srinu
  • 91
  • 1
  • 2
  • 11

3 Answers3

6

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);
Sankar
  • 6,579
  • 2
  • 26
  • 47
5

using ES6:

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