Katie7:
私は、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
これを行う方法の缶誰のアドバイス?
どうもありがとう、
ケイティ
マヌエルEguiluz:
まず、私はあなたのJSONを修正しました。その後、私はdefaultValuesオブジェクトを作成するために、JSONオブジェクトのキーを反復します。あなたの試みでは、配列としてオブジェクトを処理されています。唯一の配列は、pushメソッドを持っています。
const 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"
}
}
};
const defaultValues = {};
Object.keys(json).forEach(e => {
defaultValues[e] = json[e]["courses"].main;
});
console.log(defaultValues);