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?

3
  • Use .map instead of .forEach. Foreach doesn't return anything, whereas map returns a copy of the modified array Commented Dec 27, 2017 at 12:46
  • did it like that and my array contains now these: "[object Object] kg" Commented Dec 27, 2017 at 12:49
  • Not exact duplicate but should help you: stackoverflow.com/questions/16691833/… Commented Dec 27, 2017 at 12:53

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.