Reputation: 25
I was wondering if there is a way to transform this JSON in a way that instead of having "2020-07-06" as a key we would have a field date: "2020-07-06". Its a large dataset so I can't manually change eveything.
{
"2020-07-06": {
"food": {
},
},
"2020-07-07": {
"food": {
},
},
"2020-07-08": {
"food": {
},
},
}
Expected output:
{
"date": "2020-07-06",
"food": {
},
"date": "2020-07-07",
"food": {
},
"date: "2020-07-08",
"food": {
},
}
Upvotes: 1
Views: 59
Reputation: 322
You can use Object.entries and then map over it to create an array
const old = {
"2020-07-06": {
"food": {
},
},
"2020-07-07": {
"food": {
},
},
"2020-07-08": {
"food": {
},
},
}
const newArray = Object.entries(old).map(([key, valueObject]) => {
return { date: key, ...valueObject }
})
console.log(newArray)
Upvotes: 1
Reputation: 1120
Have a look at this snippet. Guess this is a way to start with.
const old = {
"2020-07-06": {
"food": {
},
},
"2020-07-07": {
"food": {
},
},
"2020-07-08": {
"food": {
},
},
}
const obj = Object.keys(old).map(e => {
let res = old[e]
res.date = e;
return res;
});
console.log(obj);
Upvotes: -1
Reputation: 3559
The keys has to be unique, so the only clean way to solve this is using arrays. Here you have an example of solution:
const input = {
"2020-07-06": {
"food": {
},
},
"2020-07-07": {
"food": {
},
},
"2020-07-08": {
"food": {
},
},
}
const res = Object.keys(input).map((key) => {
return {
food: input[key].food,
date: key
}
});
console.log(res)
Upvotes: 1