简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM