I have an array of objects and I would like to extract the object keys and put them in an array of possible object keys. This is the array of objects I started with :
const data = [
{
name: "Joe",
age: 23,
job: "Artist",
hoby: "Drawing",
},
{
name: "Michael",
age: 21,
job: "Engineer",
hoby: "Fishing",
},
{
name: "Jenifer",
age: 22,
job: "Dentist",
hoby: "Gardening",
},
]
I would like to get the following output :
{ header: [ 'number', 'name', 'age', 'job', 'hoby' ],
data:
[ { name: 'Joe', age: 23, job: 'Artist', hoby: 'Drawing' },
{ name: 'Michael', age: 21, job: 'Engineer', hoby: 'Fishing' },
{ name: 'Jenifer', age: 22, job: 'Dentist', hoby: 'Gardening' }
] }
Right now I'm using the following code to accomplish this :
data.unshift(header);
data.pop(data)
data.pop(data)
data.pop(data)
data.push(data1);
But it isn't returning what I would like it to return. Does anyone know an answer to my question. Thanks in advance
You can do something like this:
result = {
header: [],
data: data
};
for(const record of data) {
for(const [key, value] of Object.entries(record)) {
if(!result.header.includes(key)) {
result.header.push(key)
}
}
}
console.log(result)
But i dont get where your header number comes from...?