-1

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 ?

Lixin Li
  • 45
  • 7

3 Answers3

1

The easiest way would be to use Object.fromEntries() along with Array.prototype.map()] as below, with explanatory comments in the code:

// the initial arrays:
let keys = [ 'J', 'o', 'h', 'a', 'n'],
    entries = [ 1, 1, 1, 2, 1],
    // here we use Object.fromEntries() to create
    // an Object from a two-dimensional Array of
    // Arrays:
    result = Object.fromEntries(
      // we use Array.prototype.map() to iterate over
      // the keys Array:
      keys.map(
        // passing a reference to the current Array-value
        // ('key'), and the index of the current Array-
        // value ('index') into the function body.
        // Within the function body we return an Array
        // containing the current Array-element (which
        // becomes a key of the created-Object, and
        // the Array-element from the entries Array
        // at the same index:
        (key, index) => [key,entries[index]]
    ));
    
    console.log(result);
    /*
      {
        "J": 1,
        "o": 1,
        "h": 1,
        "a": 2,
        "n": 1
      }
    */

JS Fiddle demo.

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
1

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.

const keys = ["J", "o", "h", "a", "n"];
const values = [1, 1, 1, 2, 1];
const myObj = {}

keys.forEach((key, index) => {
  myObj[key] = values[index]
})

console.log(myObj)

Here we go through the keys array, each element in the keys array is named key.

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.

Bergur
  • 3,962
  • 12
  • 20
0

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 -

const keys = ["J", "o", "h", "a", "n"];
const values = [1, 1, 1, 2, 1];
const result = keys.reduce((acc, key, iterator) => {
return {
 ...acc, [key]: values[iterator]};
},{});

console.log("result", result);
Subhadeep
  • 149
  • 5