I have a json object and I want to take some of the values from it to create a new object in React.js. However no matter what I try I get errors relating to the value or key being undefined.
Json
{
"meat":{"drink":"Bovril", "courses":{ "main":"chicken", "pudding":"jelly" },
"vegetarian":{"drink":"milkshake", "courses":{"main":"cheese","pudding":"ice cream"},
"vegan":{"drink":"spinach juice", "courses":{"main":"lettuce","pudding":"apple"}
}
Desired results
I would like to dynamically create an object called defaultValues which matches the following if I was to hard code it. As you can see, this is created from the values in the above json file:
const defaultValues: {
meat: "chicken",
vegetarian: "cheese",
vegan: "lettuce"
}
I have tried the following based on the answer to a similar question, but it doesn't work:
My attempt
const json = Json; //this contains the contents of my json file above
const defaultValues = {};
Object.keys(json).forEach(function(key) {
defaultValues[key.meat].push([key.courses.main]);
});
Error
I keep getting the following error:
×TypeError: Cannot read property 'push' of undefined
Can anyone advise on how to do this?
Many thanks,
Katie
.push()method is for arrays, not plain objects. You're looking forObject.assign()or spread syntax.