Change object value

1

I have an array with objects similar to this:

[{
        name: '2015',
        data: [...]
        color: 'orange'
    },
    {
        name: '2016',
        data: [...]
        color: 'red'
    }
]

I would like to change the value of name to another name, type MarketShare , so instead of the year, I would have a name. This all I have to do in Javascript

The result I hope is

[{
        name: 'marketshare',
        data: [...]
        color: 'orange'
    },
    {
        name: 'marketshare',
        data: [...]
        color: 'red'
    }
]
    
asked by anonymous 01.11.2016 / 13:57

3 answers

4

You can change by directly accessing the key:

meuArray[0].name = "MarketShare";

var array = [{
  name: '2015',
  color: 'orange'
},
{
  name: '2016',
  color: 'red'
}];

array.forEach(item => {
  item.name = "Marketplace";
});

console.log(array);

Zero is the index of the array.

    
01.11.2016 / 14:07
2

Iterating the object and changing the value of the property would look something like this:

var objeto = [
               {
                 name: '2015',
                 data: [...]
                 color: 'orange'
               },
               {
                 name: '2016',
                 data: [...]
                 color: 'red'
               }
             ];

objeto.forEach(function(item) {
  item.name = 'MarketShare';
});
    
01.11.2016 / 14:16
1

One way to do it using javascript only is to iterate the object, create a new property, and delete the other property, see the example.

var meuObjeto = [{
  name: '2015',
  color: 'orange'
}, {
  name: '2016',
  color: 'red'
}];

for (var i = 0; i < meuObjeto.length; i++) {
  meuObjeto[i]['MarketShare'] = meuObjeto[i]['name'];
  delete meuObjeto[i]['name'];
}

console.log(meuObjeto);
    
01.11.2016 / 14:06