convert array to object with keys javascript code example

Example 1: js array to object with keys

const subLocationTypes = (location.subLocationTypes || []).reduce((add, cur) => {
add[cur.key] = cur.value;
return add;
}, {});

Example 2: js array into object

const names = ['Alex', 'Bob', 'Johny', 'Atta'];

// convert array to th object
const obj = Object.assign({}, names);

// print object
console.log(obj);

// {0: "Alex", 1: "Bob", 2: "Johny", 3: "Atta"}

Example 3: javascript array to object with keys

let arr = [{a: 'a', b: 1, c: 'c'}, {a: 'a', b: 2, c: 'c'}, {a: 'a', b: 3, c: 'c'}]:
 let mapped = arr.reduce (function (map, obj) { 
        map[obj.b] = obj; 
        return map;
      },{}); // reduce
console.log (mapped); // {1: {a: 'a', b: 1, c: 'c'}, 2: {a: 'a', b: 2, c: 'c'}, 3: {a: 'a', b: 3, c: 'c'}

Example 4: convert array to object javascript

const convertArrayToObject = (array, key) =>
  array.reduce(
    (obj, item) => ({
      ...obj,
      [item[key]]: item
    }),
    {}
  );

Example 5: js array to object with keys

const arr = ['a','b','c'];
const res = arr.reduce((a,b)=> (a[b]='',a),{});
console.log(res)

Example 6: javascript create array of objects with key

You will be able to get the current iteration's index for the map method through its 2nd parameter.

Example:

const list = [ 'h', 'e', 'l', 'l', 'o'];
list.map((currElement, index) => {
  console.log("The current iteration is: " + index);
  console.log("The current element is: " + currElement);
  console.log("\n");
  return currElement; //equivalent to list[index]
});