javascript - 有没有办法在 Javascript 中动态添加 JSON 字段?
问题描述
const demo = {
data:[]
};
this.state.lossGroup.forEach(element => {
const z= []
this.state.selectedExposure.map((e) => {
console.log(element,e.hazard_index.type )
if (element == e.hazard_index.type) {
z.push(e.id)
}
})
demo.data.push({ element: z });
});
我只想将数组存储在 json 文件中,元素中具有动态字段名称,即元素应替换为上循环中的值。
解决方案
如果您的密钥是动态的,您可以这样做。
[element]
是您可以处理动态键的方式。
const demo = {
data:[]
};
this.state.lossGroup.forEach(element => {
const z= []
this.state.selectedExposure.map((e) => {
console.log(element,e.hazard_index.type )
if (element == e.hazard_index.type) {
z.push(e.id)
}
})
demo.data.push({ [element] : z });
});
在这里,您可以浏览小型博客,该博客解释了如何为 json 对象设置动态键。
推荐阅读
- java - 我没有得到最后一行的所有 25 个字母
- node.js - 从 jeft 连接查询中选择特定列,TypeORM
- aggregate - 如何避免 DDD 聚合关系的 N+1 问题?
- .net - 将自动代码分析添加到遗留或已启动的代码库
- javascript - 在下载 PNG 之前将 SVG 标题添加到绘图图表
- vbscript - UFT - 随机日期
- python - Does it make any difference if we change the position of operands in a logical statement?
- ios - How pass data from one ViewController to another one Xcode?
- c++ - Can concepts be used with CRTP idiom?
- azure-devops - Copy-item command is throwing Access denied error