Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shorter/more efficient way to use the spread operator in javascript to update a key's value?

I recently got interested on using the spread operator syntax, so I tried some examples, I have this example of array:

var entities = [
  {
    "id": 1,    
    "age": 33,
    "hobby": "games"
  },
  {
    "id": 2,
    "age": 28,
    "hobby": "chess"
  },
  {
    "id": 3,
    "age": 21,
    "hobby": "comics"
  },
  {
    "age": 23,
    "hobby": "games"
  }
]

Then, to update all hobbies at "once" I do the following:

entities.forEach(function(entity, index) {
  this[index] = {...entity, hobby: "Some String to update all hobbies"};
}, entities);
console.log(entities)

Which works but I was wondering if there's a more efficient or shorter way to achieve it while using the spread operator. Any suggestions?
EDIT:
forEach is not necessary for me, or even do it in that way, I was curious on whether the spread syntax could be used (or not) to update nested values

like image 741
sab Avatar asked Dec 30 '25 01:12

sab


2 Answers

The spread operator doesn't really help when you're updating the list, like you do in your example. It's easier to just update the property of each object:

var entities = [ { "id": 1, "age": 33, "hobby": "games" }, { "id": 2, "age": 28, "hobby": "chess" }, { "id": 3, "age": 21, "hobby": "comics" }, { "age": 23, "hobby": "games" } ]

entities.forEach(entity => {
  entity.hobby = "Some String to update all hobbies";
});

console.log(entities)

The spread operator is useful if you want to create copies of objects, like you might want to do in a .map:

var entities = [ { "id": 1, "age": 33, "hobby": "games" }, { "id": 2, "age": 28, "hobby": "chess" }, { "id": 3, "age": 21, "hobby": "comics" }, { "age": 23, "hobby": "games" } ]

const newEntities = entities.map(entity =>
  ({...entity, hobby: "Some String to update all hobbies"})
);

console.log(newEntities)
like image 79
ic3b3rg Avatar answered Jan 01 '26 14:01

ic3b3rg


The spread operator will iterate over all keys in the object to copy them and their values into the new object. If you want more efficiency, don't use the spread operator. Just assign directly to each object as you iterate over the list:

entity.hobby = "Some String to update all hobbies"

Note that this modifies the object in the existing array. So you don't need to assign this[index]. Alternatively, you can use map() instead of foreach() to return a new array that is created from the existing array.

like image 38
Code-Apprentice Avatar answered Jan 01 '26 16:01

Code-Apprentice