Javascript 将对象数组转换为嵌套对象数组
因此,我有一项任务来正确地排列文件目录。为简单起见,所有文档和文件都保存为平面数组。作为显示嵌套文件的标识符,我有一个属性uniqueId,它告诉我父目录是什么。平面数组按uniqueId排序,以便每个子数组都跟随其父数组 以下是平面阵列的一个示例:Javascript 将对象数组转换为嵌套对象数组,javascript,arrays,sorting,lodash,Javascript,Arrays,Sorting,Lodash,因此,我有一项任务来正确地排列文件目录。为简单起见,所有文档和文件都保存为平面数组。作为显示嵌套文件的标识符,我有一个属性uniqueId,它告诉我父目录是什么。平面数组按uniqueId排序,以便每个子数组都跟随其父数组 以下是平面阵列的一个示例: [{ id: 1, uniqueId: '1', name: 'folder1', dir: true }, { id: 2, uniqueId: '1.2', name: 'test1', dir: false }, { id:
[{
id: 1,
uniqueId: '1',
name: 'folder1',
dir: true
},
{
id: 2,
uniqueId: '1.2',
name: 'test1',
dir: false
},
{
id: 3,
uniqueId: '1.2.3',
name: 'test2'
dir: false
},
{
id: 4,
uniqueId: '1.2.4',
name: 'test3'
dir: true
},
{
id: 3,
uniqueId: '1.3',
name: 'test23'
dir: true
},
{
id: 1,
uniqueId: '1.3.1',
name: 'test6',
dir: true
},
]
它基本上表示文件目录树:
1
1.2
1.2.3
1.2.4
1.3
1.3.1
我需要首先显示目录,即那些具有dir:true
的目录。因此,上述树将成为:
1
1.3
1.3.1
1.2
1.2.4
1.2.3
因此,作为一种解决方案,我决定最好将平面数组转换为嵌套对象,按所需方式对每个对象的子对象进行排序,然后再次转换为平面数组。这样我的平面阵列就会变成这样:
{
id: 1,
uniqueId: '1',
name: 'folder1',
dir: true
childs: [
{
id: 2,
uniqueId: '1.2',
name: 'test1',
dir: false,
childs: [
{
id: 3,
uniqueId: '1.2.3',
name: 'test2'
dir: false
},
{
id: 4,
uniqueId: '1.2.4',
name: 'test3'
dir: true
}
]},
{
id: 3,
uniqueId: '1.3',
name: 'test23'
dir: true,
childs: [
{
id: 1,
uniqueId: '1.3.1',
name: 'test23'
dir: true
}
]
}
}]
我找不到将平面转换为所需嵌套对象的方法。我已经有一个函数返回当前对象的子对象isChild(父对象,objectToCheck)。我想最好使用某种递归,但我完全被卡住了
请帮助我将其转换为所需的嵌套对象
欢迎对平面阵列排序的其他方法提出任何建议!也许有更好的方法来排序,而不需要实际转换回原力
提前多谢 您可以直接对数据进行排序,并使用
uniqueId
和父值构建树
const
input=[{id:1,uniqueId:'1',name:'folder1',dir:true},{id:2,uniqueId:'1.2',name:'test1',dir:false},{id:3,uniqueId:'1.2.3',name:'test2',dir:false},{id:4,uniqueId:'1.2.4',name:'test3',dir dir true},{id:true:'3,uniqueId:'1.3',test23',dir true},{id:1,uniqueId:'1,name:'test6',dir,
树=函数(数据){
var t={};
data.forEach(o=>{
const parent=o.uniqueId.split('.').slice(0,-1).join('.');
赋值(t[o.uniqueId]=t[o.uniqueId]| |{},o);
t[parent]=t[parent]|{};
t[parent]。children=t[parent]。children | |[];
t[parent].children.push(t[o.uniqueId]);
});
返回t['')。子对象;
}(input.sort((a,b)=>b.dir-a.dir));
控制台日志(树)代码>
。作为控制台包装{max height:100%!important;top:0;}
这些数组元素是否总是按照我们在示例输入中看到的顺序进行排序?@RahulBhobe是的,我有一个排序函数来实现这一点。谢谢你的提问,我会更新我的问题来提及这个谢谢!这将是我将平面数组转换为嵌套对象后的第二步。但我的问题是,我现在无法将平面数组转换为嵌套对象。非常感谢。这是一个完美的解决方案@Nina我唯一需要修改的是将下面的行替换为:Object.assign(t[o.uniqueId]=t[o.uniqueId]|{},o)
,因为Object.assign会覆盖现有对象t[o.uniqueId]的childs属性