Javascript:将多维数组展平为唯一路径数组

Javascript:将多维数组展平为唯一路径数组,javascript,arrays,multidimensional-array,tree,Javascript,Arrays,Multidimensional Array,Tree,我正在尝试建立一个树上所有唯一路径的列表/ 多维对象数组 假设这个数据 const data = [ { id: '1', items: [ { id: '1.1', items: [ { id: '1.1.1' }, { id: '1.1.2' }, { id: '1.1.3' }, ] } ] }, { id: '2', items: [ { id: '2.

我正在尝试建立一个树上所有唯一路径的列表/ 多维对象数组

假设这个数据

const data = [
  {
    id: '1',
    items: [
      {
        id: '1.1',
        items: [ { id: '1.1.1' }, { id: '1.1.2' }, { id: '1.1.3' }, ]
      }
    ]
  },
  {
    id: '2',
    items: [
      {
        id: '2.1',
        items: [ { id: '2.1.1' }, { id: '2.1.2' }, { id: '2.1.3' },  ]
      },
      {
        id: '2.2',
        items: [ { id: '2.2.1' } ]
      }
    ]
  }
]
我需要以这样的数组结构结束

const result = [
  ['1', '1.1', '1.1.1'],
  ['1', '1.1', '1.1.2'],
  ['1', '1.1', '1.1.3'],
  ['2', '2.1', '2.1.1'],
  ['2', '2.1', '2.1.2'],
  ['2', '2.1', '2.1.3'],
  ['2', '2.2', '2.2.1']
];
其中,每个条目都是原始树结构下唯一路径的数组

我很难将每个路径作为单独的条目。到目前为止,我所拥有的将返回到较低级别的路径,并将底层ID附加到当前路径

function flatten(items, path = []) {
  let result = [];
  items.forEach( item => {
    path.push(item.id);
    if (item.items && item.items.length) {  
      result.push(flatten(item.items, path.slice(0) )); //slice to clone the array
    }
    else {
      result.push(...path);
    }
  });

  return result;
}
这是一把JS小提琴


foreach回调中更新的路径是共享的。应该是本地的

function flatten(items, path = []) {
  let result = [];
  items.forEach(item => {
    let localPath = path.slice(0);
    localPath.push(item.id);
    if (item.items && item.items.length) {  
      result.push(flatten(item.items, localPath));
    } else {
      result.push(localPath);
    }
  });
  return result;
}

可以使用内部方法将所有完整路径推送到同一结果数组:

const data=[{“id”:“1”,“items”:[{“id”:“1.1”,“items”:[{“id”:“1.1.1”},{“id”:“1.1.2”},{“id”:“1.1.3”}]},{“id”:“2”,“items”:[{“id”:“2.1.1”},{“id”:“2.1.1”},{“id”:“2.1.3”},{“id”:“2.2.2”},{“id”:“2.2”}]
函数展平(项目){
常量结果=[];
常量iterateItems=(项,路径=[])=>
items.forEach(({id,items})=>{
const localPath=[…路径,id];
若有(项目)
迭代项(items,localPath);
其他的
结果推送(localPath);
});
项目(项目);
返回结果;
}
console.log(展平(数据))
您可以使用
reduce()
方法创建递归函数并返回数组。您可以使用
concat()
方法创建
prev
数组的副本,以便在每个递归级别上都有新的副本,因为数组是通过引用传递的,否则您将更改原始数组

const data=[{“id”:“1”,“items”:[{“id”:“1.1”,“items”:[{“id”:“1.1.1”},{“id”:“1.1.2”},{“id”:“1.1.3”}]},{“id”:“2”,“items”:[{“id”:“2.1.1”},{“id”:“2.1.1”},{“id”:“2.1.3”},{“id”:“2.2.2”},{“id”:“2.2”}]
函数构建(数据,上一个=[]){
返回数据.reduce(函数(r,e){
const copy=上一个concat(e.id)
如果(e.items)r=r.concat(构建(e.items,复制))
else r.push(复制)
返回r;
}, [])
}
const result=构建(数据);
console.log(结果)