0

I have an array looking like this:

myArray = [[EnterNode {name: "name1", _value_: 12.32 }],
           [EnterNode {name: "name2", _value_: 42.39 }],
           [EnterNode {name: "name3", _value_: 77.32 }],
           [EnterNode {name: "name4", _value_: 52.31 }],
           ...
]

I don't know what EnterNode means but this is how it looks like when I print it in the console.

I want to each _value_ to concatenate a string, for example " kg" so after this procedure the array to look like this:

myArray = [[EnterNode {name: "name1", _value_: "12.32 kg" }],
           [EnterNode {name: "name2", _value_: "42.39 kg" }],
           [EnterNode {name: "name3", _value_: "77.32 kg" }],
           [EnterNode {name: "name4", _value_: "52.31 kg" }],
           ...
]

I tries to do it like this:

myArray.forEach(_value_ => _value_ + " kg") but I get undefined as result.

Any suggestions?

Leo Messi
  • 5,157
  • 14
  • 63
  • 125
  • Use `.map` instead of `.forEach`. Foreach doesn't return anything, whereas map returns a copy of the modified array – user184994 Dec 27 '17 at 12:46
  • did it like that and my array contains now these: `"[object Object] kg"` – Leo Messi Dec 27 '17 at 12:49
  • Not exact duplicate but should help you: https://stackoverflow.com/questions/16691833/modify-object-property-in-an-array-of-objects – Rajesh Dec 27 '17 at 12:53

1 Answers1

1

myArray.forEach(value => value + " kg") but I get undefined as result.

Because you are not saving the value back to _value_ property of each item of the array

Make it

myArray.forEach( obj => ( obj._value_ += " kg" ) ); 

observe that iteration happens on the item of the array rather than _value_

Demo

var myArray = [
   {name: "name1", _value_: 12.32 },
   {name: "name2", _value_: 42.39 },
   {name: "name3", _value_: 77.32 },
   {name: "name4", _value_: 52.31 }
];

myArray.forEach( obj => ( obj._value_ += " kg" ) ); 
 
console.log( myArray );
gurvinder372
  • 66,980
  • 10
  • 72
  • 94