给定以下 JSON 结构,
#JSON 1
{
"objects":
[
{
"type": "chocolate",
"id": "c1"
},
{
"type": "sweet",
"id": "s1"
}
]
}
如何使用 Javascript 动态附加数据?像这样:
#JSON 2
[
{
"data": {
"type": "chocolate",
"id": "c1"
}
},
{
"data": {
"type": "sweet",
"id": "s1"
}
}
]
我使用获取 API 来读取文件,因为它是一个巨大的 JSON 文件。 而且我不想对类型和 ID 进行硬编码。执行此操作的更好方法是什么?
最佳答案
显然您是从 fetch 中得到这个结果的,但是为了演示您需要做什么,我将它内联初始化
let result = {
"type": "test",
"id": "123",
"objects":
[
{
"type": "chocolate",
"id": "c1"
},
{
"type": "sweet",
"id": "s1"
}
]
};
let finalResult = result.objects.map(data => ({data}));
console.log(finalResult);
你提到使用 fetch - 它就像
fetch(url)
.then(result => result.json())
.then(result => result.objects.map(data => ({data})))
.then(finalResult => {
// here the result is in the format you want
console.log(finalResult);
});
关于javascript - 将数据动态附加到现有的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50893414/