我正在遍历2d数组["cat","dog","bird"]
在那个循环中,我将如何动态构造看起来像这样的多级JSON?理想的答案是构造json对象并将其分配给变量。预期的格式如下所示,您可以假设单词代表迭代变量,或者在相反的情况下,它是字符串串联“-” +迭代变量。
{"cat":
{
"name":"cat",
"nickname":"cat",
"oppositeName":"-cat"
}
},
{"dog":
{
"name":"dog",
"nickname":"dog",
"oppositeName":"-dog"
}
},
{"bird":
{
"name":"bird",
"nickname":"bird",
"oppositeName":"-bird"
}
}
最佳答案
您可以执行以下操作:
const final = {};
['cat', 'dog', 'bird'].forEach(creature => {
final[creature] = {
"name": creature,
"nickname": creature,
"oppositeName": `-${creature}`
}
})
console.log(final)
关于javascript - 如何在此2d循环中动态创建类似的多级JSON?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46016550/