Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change properties of every item in an array?

I need to set the value of every item in this array, counting up.

So, for example, path[0].value = 1, path[1].value = 2 etc...

EDIT: I'm looking for the most efficient way to do this.

I think a for loop is the best way, but I want to learn other ways. Can it be done with the map() method or forEach()? What about a for... in statement? I'd like to do it with pure JS, but if you can teach me a better way with jQuery, I'd be interested to learn that too.

Thanks in advance.

function Cell(x,y){
    this.xCoordinate = x;
    this.yCoordinate = y;
    this.value;
}
var path = [new Cell(0,0), new Cell(0,1), new Cell(0,2)];
like image 264
fatblacklip Avatar asked Mar 08 '16 22:03

fatblacklip


People also ask

How do you change all elements in an array?

To change the value of all elements in an array:Use the forEach() method to iterate over the array. The method takes a function that gets invoked with the array element, its index and the array itself. Use the index of the current iteration to change the corresponding array element.

Can you change the elements in an array?

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

How do you change the properties of an object?

Setting Properties of Existing Objects After you have created an object, you can set or change its properties by calling the property directly with the dot operator (if the object inherits from IDL_Object) or by calling the object's SetProperty method.


2 Answers

You can use a for loop or forEach:

for(var i=0; i<path.length; ++i)
  path[i].value = i+1;
path.forEach(function(cell, i) {
  cell.value = i + 1;
});

Better avoid for...in because of Why is using “for…in” with array iteration such a bad idea?.

like image 94
Oriol Avatar answered Sep 30 '22 18:09

Oriol


If you have an existing array, you can use map.

var path = [0,1,2].map( x => new Cell(0, x))

or to mutate

path = path.map( x => {
  x.value = x.yCoordinate - 1
  return x 
}) 
like image 29
Fresheyeball Avatar answered Sep 30 '22 19:09

Fresheyeball