var a = {};
var b = [1,2,3,4];
var c = ['a', 'b', 'c', 'd'];
b.map((i) => {
c.map((j) => {
a[j] = i
})
});
console.log(a);
In above code I am expecting the output to be {a:1, b:2, c:3, d:4}. But It's giving {a:4, b:4, c:4, d:4}. Same is the case with using for loops with let keyword instead of maps. What's the reason behind this and how to fix it to get the desired output?
CodePudding user response:
The issue is because each iteration of your loop overwrites the property values in your object (i.e. a
, b
, c
and d
) with the current value of i
. Therefore when the loops end, the properties have all been set to the last value of i
, which is 4
.
To achieve your expected outcome, you don't need the inner map()
call. You can access the c
array by index to align it with the values from the b
array,
In addition, note that map()
should used to transform the values of an existing array into a new array. As your logic is not doing this, it's actually using the loop-like behaviour of map()
to amend an object, you should use forEach()
instead.
const a = {};
const b = [1, 2, 3, 4];
const c = ['a', 'b', 'c', 'd'];
b.forEach((n, index) => {
a[c[index]] = n;
});
console.log(a);
CodePudding user response:
You're essentially doing this:
First it takes the 1 from your "b" array. Then in a loop it is adding each letter from the "c" array to the "a" object and giving it the current "b" value, which is always the same value that loop. So after 1 loop you end with
{ a: 1, b: 1, c:1, d:1 }
Then for the second loop it is essentially mapping again and overwriting the "a" object like this:
{ a: 2, b: 2, c: 2, d:2 }
This goes on until every value is 4.