将对象的隐蔽平面数组转换为嵌套对象数组

时间:2019-09-14 06:41:59

标签: javascript arrays multidimensional-array nested mapping

我无法将平面数组转换为多层数组


[{
    code: "1",
    text: "FatturaElettronicaHeader",
  },
  {
    code: "1.1",
    text: "DatiTrasmissione",
  },
  {
    code: "1.1.5",
    text: "ContattiTrasmittente",
  },
  {
    code: "1.1.5.1",
    text: "Telefono",
  },
  {
    code: "1.1.5.2",
    text: "Email",
  },
  {
    code: "1.2",
    text: "CedentePrestatore",
  }
]
我想要它,以便如果数组元素代码包含另一个数组元素的代码,则它应该是该元素的子级。因此1.1和1.2都是1.的子代,那么1.1.5仅是1.1的子代。新数组中每个对象应该只有一个

1 个答案:

答案 0 :(得分:1)

您可以使用forEach循环创建嵌套树结构以遍历数组,然后对于每个对象,可以使用split获取路径数组,并可以使用reduce方法创建基于以下内容的嵌套结构路径数组。

const data = [{"code":"1","text":"FatturaElettronicaHeader"},{"code":"1.1","text":"DatiTrasmissione"},{"code":"1.1.5","text":"ContattiTrasmittente"},{"code":"1.1.5.1","text":"Telefono"},{"code":"1.1.5.2","text":"Email"},{"code":"1.2","text":"CedentePrestatore"}];

const result = [], level = {result}
data.forEach(e => {
  e.code.split('.').reduce((r, k) => {
    if(!r[k]) {
      r[k] = {result: []}
      r.result.push({...e, children: r[k].result})
    }
    return r[k];
  }, level)
})

console.log(result);

您也可以使用两个reduce方法而不是forEach循环来获得相同的结果。

const data = [{"code":"1","text":"FatturaElettronicaHeader"},{"code":"1.1","text":"DatiTrasmissione"},{"code":"1.1.5","text":"ContattiTrasmittente"},{"code":"1.1.5.1","text":"Telefono"},{"code":"1.1.5.2","text":"Email"},{"code":"1.2","text":"CedentePrestatore"}];

const result = data.reduce((level, {code, ...rest}) => {
  return code.split('.').reduce((r, k) => {
    if(!r[k]) {
      const children = [];
      r[k] = {result: children}
      r.result.push({code, ...rest, children})
    }
    return r[k]
  }, level), level
}, {result: []}).result

console.log(result);