Change object value

Asked

Viewed 16,786 times

1

I have an array with objects similar to this:

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

I’d like to change the value of name for another name, like MarketShare, then instead of the year, I would have a name. This I have to do in Javascript

The result I expect is

[{
        name: 'marketshare',
        data: [...]
        color: 'orange'
    },
    {
        name: 'marketshare',
        data: [...]
        color: 'red'
    }
]
  • @Lucascosta I edited the question

3 answers

6


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.

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

console.log(JSON.stringify(objeto));

Using ES6:

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

const resultado = objeto.map((item) => ({ ...item, name: 'MarketShare' }));

console.log(JSON.stringify(resultado));

Operador Spread

The spread operator allows an expression to be expanded to places where multiple arguments (by function calls) or multiple elements (by literal array) are expected.


Scattering Syntax (Spread syntax).

Scattering Syntax (Spread syntax) allows an iterable object such as an array expression or a string to be expanded where zero or more arguments (for function calls) or elements (for literal arrays) are expected, or an object to be expanded where zero or more pairs property:value (for literal objects) are expected.

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers));
// expected output: 6

console.log(sum.apply(null, numbers));
// expected output: 6

1

One way to do it using javascript only, is to iterate the object, create a new property and delete the other, see in 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);

  • your code works, but it’s not the way I need it, I think I missed out on the question. I edited it, give a look there please.

  • The @Lucascosta answer your question then. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.