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)
4castle
  • 32,613
  • 11
  • 69
  • 106
Doom
  • 23
  • 2

2 Answers2

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}));
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)
Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
  • It works Yeah, can explain why, I didnt understand why I need to parse it sense numbers isnt a string – Doom Jul 25 '16 at 14:11
  • It's because `roots` and `numbers` point out to the same object. – Murat Karagöz Jul 25 '16 at 14:12
  • 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 Jul 25 '16 at 14:12
  • @4castle well I was using forEach firstly but I want to play with map a bit, btw love your comment on top – Doom Jul 25 '16 at 14:15
  • @4castle why did you remove the json tag, from question? Murat K. used `JSON.parse(JSON.stringify(numbers))`. – Reporter Jul 25 '16 at 14:18
  • @reporter Because the question isn't about JSON. JSON is a string. The answer only used `JSON.stringify()` to make a deep copy of the array. – 4castle Jul 25 '16 at 14:20
  • Using `JSON.parse(JSON.stringify` is certainly a brute force way to clone an object, and not even necessary here. –  Jul 25 '16 at 14:26