I have two arrays:
[ 'J', 'o', 'h', 'a', 'n']
[ 1, 1, 1, 2, 1]
I would like to use the first one as the object keys and the second one as object values. The result should be:
{ "J": 1, "o": 1, "h": 1, "a": 2, "n": 1}
Is this achievable with JavaScript ?
3
Answers
The easiest way would be to use
Object.fromEntries()
along withArray.prototype.map()
] as below, with explanatory comments in the code:JS Fiddle demo.
References:
Array.prototype.map()
.Object.prototype.fromEntries()
.As @PCDSandwichMan mentioned you can use reduce. See:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
Reduce goes through the array and returns a single value. It can sometimes be littly tricky to see what is going on although it looks nice as a one-liner
If you want to see a more transparent method you can start with empty array, loop through the array and add a property to the object for each element in the array.
Here we go through the
keys
array, each element in thekeys
array is namedkey
.We then use the brack notation of an object to create a property and assign the value from the
values
array that is at the same index/location as the key element.This question is similar to Convert array to object keys
Adding an extra iterator as third argument to track the index will do the trick for you –