javascript - 使用三元操作的 JSON 遍历
问题描述
我有以下代码:
let jsonObject = {one: {two: {three: {}}}};
let contents = [ ["text", "one", "two"], ["other text", "one", "two", "three", "four"] ... ]
contents.forEach(content => {
jsonObject[content[1] ? content[1] : ""][content[2] ? content[2] : ""][content[3] ? content[3] : ""] = content[0];
})
根据哪些变量 ( content[1-3]
) 返回true
布尔值,它应该将 JSON 移动得更深,直到它不能再移动,然后最终设置content[0]
. 但是,我的代码将不起作用,因为jsonObject[""]
(连同undefined
或null
代替""
)会尝试将对象更深地移动到不存在的键/对中。我怎样才能成功地用一条线做到这一点?
解决方案
这有帮助吗?
contents.forEach(content => {
if(content[1] && content[2] && content[3]) {
jsonObject[content[1]][content[2]][content[3]] = content[0];
} else if(content[1] && content[2]) {
jsonObject[content[1]][content[2]] = content[0];
} else if(content[1]) {
jsonObject[content[1]] = content[0];
};
});
推荐阅读
- php - in_array 函数可能失败有什么限制吗?
- java - 如何从 Tablayout 中删除高程?
- modeling - 如何在富文本编辑器中拥有变量
- python - 了解python中的范围
- python - 遍历 Pandas 数据框列中的列表元素并匹配不同数据框中的值
- php - PHP PDO选择查询在大量记录上失败
- java - 小米杀前台服务
- mysql - 只有当存储过程运行两次时,它才会返回完整的结果集
- discord.py-rewrite - 确定用户是否为成人 (discord.py)
- docker - Docker-compose - 无法为服务 postgres 创建容器