How to convert array of objects into enum like key value pair in javascript?

Viewed 86

I have an array

const a = [
  { name: "read-web-courses" },
  { name: "example" },
  { name: "t_gql" },
  { name: "ddddd" },
];

I am trying it to reduce it to the below given output , However I am stuck

Output

{0:"read-web-courses",1:"example",2:"t_gql",3:"ddddd"}
3 Answers

You could map the wanted property and assign the pairs to the object.

const
    array = [{ name: "read-web-courses" }, { name: "example" }, { name: "t_gql" }, { name: "ddddd" }],
    result = Object.assign({}, array.map(({ name }) => name));

console.log(result);

This is accomplished using Array#reduce, where you can use the index from the reduce callback as the key of the new object:

const a = [ { name: "read-web-courses" }, { name: "example" }, { name: "t_gql" }, { name: "ddddd" }];

const res = a.reduce((r, o, i) => {
  r[i] = o.name;
  return r;
}, {});

console.log(res);

Also one more approach using Object#fromEntries and Array#map, where each object is converted to an array of key, value pairs:

const a = [ { name: "read-web-courses" }, { name: "example" }, { name: "t_gql" }, { name: "ddddd" }];

const res = Object.fromEntries(a.map((o, i) => [i, o.name]));
console.log(res)

You can use Array.reduce like below.

  const a = [
    { name: "read-web-courses" },
    { name: "example" },
    { name: "t_gql" },
    { name: "ddddd" },
  ];
  
  const convert = arr => (
    arr.reduce((total, value, index) => {
      total[index] = value.name;
      return total;
    }, {})
  )

  console.log(convert(a));
Related