After making an API call, I am capturing a json response. My goal is to extract the keys and generate an array of objects dynamically, regardless of the number of keys in the response.
To get the keys, I have implemented the following function:
const json_getAllKeys = data => {
const keys = data.reduce((keys, obj) => (
keys.concat(Object.keys(obj).filter(key => (
keys.indexOf(key) === -1))
)
), [])
return keys
}
Running this function on a sample json returns an array containing the keys:
['name','username', 'email']
Now, I want to utilize this array to create objects that resemble the following structure:
[
{
name: "name",
username: "username",
email: "Email",
}
];
My attempt at mapping the array resulted in multiple objects due to the loop repetition, which isn't desirable for my intended outcome.
keys.map(i=>({i:i}))
[
{ i: 'id' },
{ i: 'name' },
{ i: 'username' },
{ i: 'email' }
]
If you have any suggestions or tips on how to achieve a single object from this array, please share!
Thank you for your assistance! :D