Home > Blockchain >  Javascript map to array, get and set
Javascript map to array, get and set

Time:05-21

let myMap = new Map();

myMap.set(1, [1,2,3]);
myMap.set(1, myMap.get(1).push(4));

console.log(myMap);

In the above code, 1 is mapped to the array [1,2,3]. Then I want to add 4 to this array. However when I do a console.log, myMap turns out to be just 4 and not the array [1, 2, 3, 4]

Why?

But if I do

olds = myMap.get(1);
olds.push(4)

then things work as expected.

CodePudding user response:

It's because push returns the new length of the array which happens to be 4 in this case and you are setting it to be the new value. You are basically doing this:

// ...
const new_length = myMap.get(1).push(4);
myMap.set(1, new_length);

CodePudding user response:

Your instruction myMap.set(1, myMap.get(1).push(4)); actually translates to myMap.set(1, 4) as the length of the array is returned on the push method.

I think what you want to do is myMap.get(1).push(4) which will assign [1, 2, 3, 4] to 1 in myMap. (but still return the length of the array)

  • Related