Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert an array of objects into an array of objects with mapped key-value pairs

It is hard to put into words, so If anyone could help me with the title of the question, thanks in advance. At the end of the day, I have an array like so;

[ 
  {
    field: "firstname",
    value: "John"
  },
  {
    field: "lastname",
    value: "Doe"
  },
  {
    field: "hobbies",
    value: "singing, basketball"
  },
]

and the desired output will be like below;


[ 
  {
   "firstname":"John"
  },
  {
    "lastname":"Doe"
  },
  {
    "hobbies" :"singing, basketball"
  },
]

The closest question I could find similar to mine was this one: How to convert an array into an object in javascript with mapped key-value pairs?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

let output = [ 
    {
        field: "firstname",
        value: "John"
    },
    {
        field: "lastname",
        value: "Doe"
    },
    {
        field: "hobbies",
        value: "singing, basketball"
    },
].map(a => ({[a.field]: a.value}))

console.log(output)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading