From single array convert to an array of object with keys coming from a JSON response -JAVASCRIPT-

I am receiving a json response from an API call. I need to store its keys, and create an array of an object. I am intending to this array of an object is created dynamically no matter the keys of the response.

I’ve already got the keys like this:

  const json_getAllKeys = data => {
   const keys = data.reduce((keys, obj) => (
      keys.concat(Object.keys(obj).filter(key => (
        keys.indexOf(key) === -1))
      )
    ), [])
    return keys 
}

That returned an array (using a sample json):

['name','username', 'email']

But I am trying to use that array to create an array of object that looks like this one

[
    {
      name: "name",
      username: "username",
      email: "Email",
    }
];

I’ve been trying mapping the array, but got multiple objects because of the loop, and I need a single one to make it work.

keys.map(i=>({i:i}))

[
  { i: 'id' },
  { i: 'name' },
  { i: 'username' },
  { i: 'email' }
]

Any hint would be useful!

Thanks in advance 😀

4 thoughts on “From single array convert to an array of object with keys coming from a JSON response -JAVASCRIPT-”

  1. 176328 682461Once I originally commented I clicked the -Notify me when new feedback are added- checkbox and now every time a remark is added I get four emails with exactly the same comment. Is there any indicates you possibly can remove me from that service? Thanks! 381950

    Reply
  2. 435542 503355Thanks for your time so significantly for your impressive and incredible guide. I will not be reluctant to endorse your web sites to any individual who need to receive direction on this difficulty. 32003

    Reply

Leave a Comment