2

Why map is changin' the old array numbers ? I don't want to change the old array, I want to edit it (key * 2) and put it in new array roots. Can someone explain what the problem is?

var numbers = [{key:1,prop:"ok"}, {key:2,prop:"ok"}, {key:3,prop:"ok"}];
var roots = numbers.map(index => {
  index.key = index.key * 2
  return index
})

console.log('numbers', numbers)
console.log('roots', roots)

7
  • Just for you: Your "array" is a json object, not a good plain array. :-) And which Javascript framework did you use? Commented Jul 25, 2016 at 14:04
  • @reporter I think you wrote that backwards. There's no json here Commented Jul 25, 2016 at 14:05
  • okey thx, any idea to achieve that ? Commented Jul 25, 2016 at 14:06
  • 2
    @reporter dude are you serious ? THIS IS A PLAIN JAVASCRIPT Commented Jul 25, 2016 at 14:07
  • map doesn't protect you from modifying reference types. Only primitive types. Commented Jul 25, 2016 at 14:10

2 Answers 2

2

In your case, the simplest approach would be

var numbers = [{key:1,prop:"ok"}, {key:2,prop:"ok"}, {key:3,prop:"ok"}];
var roots = numbers.map(elt => ({
  key: elt.key * 2,
  prop: elt.prop
}));

In other words, return new objects from map.

Or if you prefer, you can destructure the parameter:

var roots = numbers.map(({key, prop}) => ({key: key * 2, prop}));
Sign up to request clarification or add additional context in comments.

1 Comment

I would also rename index to object
1

Seems like there is no straight-forward way to copy a array without references. But this works tho:

var numbers = [{key:1,prop:"ok"}, {key:2,prop:"ok"}, {key:3,prop:"ok"}];
var roots = JSON.parse(JSON.stringify(numbers)); 
roots.map(index => {
  index.key = index.key * 2
  return index
})

console.log('numbers', numbers)
console.log('roots', roots)

7 Comments

It works Yeah, can explain why, I didnt understand why I need to parse it sense numbers isnt a string
It's because roots and numbers point out to the same object.
If you aren't going to capture the result of the map, you might as well use forEach so you don't create a 3rd, unused array.
@4castle well I was using forEach firstly but I want to play with map a bit, btw love your comment on top
@4castle why did you remove the json tag, from question? Murat K. used JSON.parse(JSON.stringify(numbers)).
|

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.