通过JavaScript映射Json数据

问题描述 投票:-1回答:2

我有一个想要以其他格式保存的Json数据。

我的原始json数据是:

{
  "info": {
    "file1": {
      "book1": {
        "lines": {
          "102:0": [
            "102:0"
          ],
          "105:4": [
            "106:4"
          ],
          "106:4": [
            "107:1",
            "108:1"
          ]
        }
      }
    }
  }
}

而且我想按以下方式映射它:

{
  "name": "main",
  "children": [
    {
      "name": "file1",
      "children": [
        {
          "name": "book1",
          "group": "1",
          "lines": [
            "102",
            "102"
          ],
          [
            "105",
            "106"
          ],
          [
            "106",
            "107",
            "108"
          ]
        }
      ],
      "group": 1,

    }
  ],
  "group": 0
}

但是书的数量和文件的数量将会更多。在这行代码中,“”内的第一部分(在:之前)被获取(“ 106:4”变为“ 106”)。键的数字为1,然后值的数字为列表([“ 106”,“ 107”,“ 108”])。

到目前为止,我尝试了以下代码:

  const before = JSON.parse(JSON.stringify(json))
  const filenames = Object.keys(before["info"]);

  const after = {
    name: 'main',
    children: [],
    group: 0,
    lines: []
  }

// I am not sure about this nested for loops

for(let x in filenames)
{
  var booknames = Object.keys(before["info"][filenames[x]]);
  for(let y in booknames){
    var cf1 = Object.keys(before["info"][filenames[x]][booknames[y]]["lines"]);
    var cf2 = Object.values(before["info"][filenames[x]][booknames[y]]["lines"]);
for (let z1 in cf1){
    var cf = cf1[z1].split(":")[0];
}
for (let z2 in cf2){
    var cfn = cf2[z2].split(":")[0]; // error: Uncaught TypeError: cf2[z2].split is not a function
}
   }

}

  const children = filenames.map((filename, idx) => {
    const innerChildren = Object.keys(before["info"][filename]).map((n) => ({
      name: n,
      group: idx + 1,
    }))

    return ({
      name: filename,
      children: innerChildren,
      group: idx + 1,
    });
  })

  after.children = children;

  console.log(after);

我试图弄清楚如何获得所需的值并正确映射。我认为我的for循环嵌套不是一个好主意。如果您能帮助我解决问题,我将不胜感激。

javascript arrays json loops stringify
2个回答
2
投票

您可以使用reduce方法并创建递归函数来构建嵌套结构。

const data = {"info":{"file1":{"book1":{"lines":{"102:0":["102:0"],"105:4":["106:4"],"106:4":["107:1","108:1"]}}}}}

function build(data) {
  return Object.entries(data).reduce((r, [key, value]) => {
    const obj = {}

    if (key !== 'lines') {
      obj.name = key;
      obj.children = build(value)
    } else {
      if (!obj.lines) obj.lines = [];
      Object.entries(value).forEach(([k, v]) => {
        obj.lines.push([k, ...v].map(e => e.split(':').shift()))
      })
    }

    r.push(obj)
    return r;
  }, [])
}

const result = build(data);
console.log(result);

-1
投票

我无法理解group属性背后的逻辑,因此您可能需要为此添加更多信息,但是对于其余部分,您可以尝试使用这两个函数将对象递归转换为要获取的内容。

var a = JSON.parse('{"info":{"file1":{"book1":{"lines":{"102:0":["102:0"],"105:4":["106:4"],"106:4":["107:1","108:1"]}}}}}');

var transform = function (o) {
    return Object.keys(o)
            .map((k, ki, ko)  => { 
                  return {"name": k, "children": (k === "lines" ? parseLines(o[k]) : transform(o[k])) } 
              }
            )
}

var parseLines = function (lines) {
    return Object.keys(lines)
            .map(v => [v.split(':')[0], ...(lines[v].map(l => l.split(":")[0]))])
}

console.log(JSON.stringify(transform(a)[0], null, 2));
© www.soinside.com 2019 - 2024. All rights reserved.