我有一个 json 对象,我想从中获取一些值来在 React.js 中创建一个新对象。但是,无论我尝试什么,我都会收到与未定义的值或键相关的错误。
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"}
}
期望的结果
如果我要对其进行硬编码,我想动态创建一个名为defaultValues的对象,该对象与以下内容匹配。如您所见,这是根据上述 json 文件中的值创建的:
const defaultValues: {
meat: "chicken",
vegetarian: "cheese",
vegan: "lettuce"
}
我根据类似问题的答案尝试了以下方法,但它不起作用:
我的尝试
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]);
});
错误
我不断收到以下错误:
×TypeError: Cannot read property 'push' of undefined
谁能建议如何做到这一点?
繁花如伊
慕桂英4014372
白衣染霜花
相关分类