首页 > 解决方案 > 使用三元操作的 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[""](连同undefinednull代替"")会尝试将对象更深地移动到不存在的键/对中。我怎样才能成功地用一条线做到这一点?

标签: javascriptnode.jsjson

解决方案


这有帮助吗?

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];
  };
});


推荐阅读