0 votes
by (1.1k points)
edited by

A question about how to modify an equal variable within all objects in an array. An example, there are two children in the family one is 2 years and the other 4 years, two objects in an array.

<<set $myFamily = [
    { name: 'Anna', age: 2 },
    { name: 'Carlos', age: 4 }
]>>

Each year they age one year... This matrix can increase with new people. In that case I need to change the age in all of them. I would like to ask how to do this in JS as well.

1 Answer

0 votes
by (159k points)
selected by
 
Best answer

edited: to include TheMadExile's suggestion.

There are a number of methods you can use, three of them being:

1. The range variation of the <<for>> macro combined with a <<set>> macro.

<<for _child range $myFamily>>
	<<set _child.age += 1>>
<</for>>


2. The JavaScript <Array>.forEach() function.

<<run $myFamily.forEach(function (child) { child.age += 1; })>>


3. The JavaScript <Array>.map() function.

<<run $myFamily.map(function (child) { child.age += 1; return child; })>>
by (1.1k points)
But does the map method not modify an original array?
by (159k points)

You can use the following code to test both the before and after state of the $myFamily variable, it's the same code that I used to test both of the examples I gave.

<<for _child range $myFamily>>
	name: _child.name age: _child.age
<</for>>

 

by (68.6k points)
edited by

Using <Array>.map() for this is simply bizarre.  <Array>.forEach() would be a much better fit for this situation.  For example:

<<run $myFamily.forEach(function (person) { person.age += 1; })>>

 

But does the map method not modify an original array?

Normally, you use <Array>.map() to return a new array whose members are created by the supplied callback.  Thus, you are correct in that <Array>.map() does not modify the original array.

That holds true in Greyelf's example (and mine within this reply).  It does not actually modify the original array itself.  It modifies the generic objects within the array via their references.

Objects in JavaScript are what's known as a reference type.  Meaning, you never actually hold the object itself, like you would one of the primitive types (e.g., booleans, numbers, and strings), but instead a reference to the object.  Thus, the callback in Greyelf's example can modify the objects within the array without modifying the array itself because it's being passed references to the objects.

...