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 ?
>Solution :
You can use Array.prototype.reduce to iterate over the arrays and create the object:
const keys = ["J", "o", "h", "a", "n"];
const values = [1, 1, 1, 2, 1];
// We are using reduce to iterate over the keys array and create an object
const result = keys.reduce(
(
acc, // The first argument is the accumulator, which is the object we are building
key, // The second argument is the current value, which is the current key
i // The third argument is the index, which is the current index
) => {
// We are returning the accumulator with the current key and value
return {
...acc, // We are spreading the accumulator to keep the previous values
[key]: values[i], // We are adding the current key and value
};
},
{} // The second argument for reduce is the initial value, which is an empty object this is used as the first value of the accumulator
);
console.log("result", result);