简体   繁体   English

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

[英]Covert flat array of objects to array of nested objects

i'm having trouble turning a flat array to a multi nested array 我在将平面数组转换为多嵌套数组时遇到麻烦


[{
    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",
  }
]

i want it so that if an array elements code includes the code of another array element, it should be a child of that element. 我想要这样,如果数组元素代码包含另一个数组元素的代码,则它应该是该元素的子级。 So 1.1 and 1.2 are both children of 1. then 1.1.5 is child of 1.1 only. 因此1.1和1.2都是1.的子代,那么1.1.5仅是1.1的子代。 there should only be one of each object in the new array 新数组中每个对象应该只有一个

You can create nested tree structure using forEach loop to iterate through array and then for each object you can use split to get path array and reduce method to create nested structure based on the path array. 您可以使用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); 

You can also use two reduce methods instead of forEach loop to get the same 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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM