{
"eggs":{
"protein":5.5,
"count":10,
"serving":3,
"_comment":"Serving is per eggs"
},
"chicken":{
"protein":23,
"weight":900,
"serving":4.5,
"_comment":"Serving is per 100 grams"
},
"kwark":{
"protein":8.5,
"weight":1000,
"serving":2
},
"milk":{
"protein":3.5,
"weight":2000,
"serving":1
},
"oats":{
"protein":14,
"weight":450,
"serving":1
},
"cottageCheese":{
"protein":19,
"weight":200,
"serving":1
}
}
命名为 Json 的对象
const nutrition = require("./nutritionalValues.json");
调用 json 对象在同一个文件中工作。
现在我要做的是创建与 JSON 对象的键同名的变量。所以
Object.keys(nutrition) // ["eggs", "chicken", "kwark", "milk", "oats", "cottageCheese"]
可以立即分配变量
let {eggs, chicken, kwark, milk, oats, cottageCheese} = nutrition;
但是,如果我在 JSON 文件中有数千个项目怎么办。如何以编程方式创建这些变量?和/或有更好的方法来管理这个吗?