Ali
Ali

Reputation: 485

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

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"}

Upvotes: 2

Views: 428

Answers (3)

Amardeep Bhowmick
Amardeep Bhowmick

Reputation: 16908

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)

Upvotes: 1

michael
michael

Reputation: 4173

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));

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386654

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);

Upvotes: 3

Related Questions