JavaScript 数组对象排序:根据前后关系归类并添加 outerId 属性
现有数组对象如下: [ { id: 1, list: [ { preId: '', nextId: '', id: 'N1', } ] }, { id: 2, list: [ { preId: 'N4', nextId: '', id: 'N2', } ] }, { id: 3, list: [ { preId: '', nextId: 'N6', id: 'N3', } ] }, { id: 4, list: [ { preId: 'N6', nextId: 'N2', id: 'N4', } ] }, { id: 5, list: [ { preId: '', nextId: '', id: 'N5', } ] }, { id: 6, list: [ { preId: 'N3', nextId: 'N4', id: 'N6', } ] } ];
// 条件:
// list的对象中: // preId 代表排序在该对象 前面的对象的id; // nextId: 代表排序在该对象 后面的对象的id; // 原数组中,每个list中只会有一个对象;
// 目的: // 现在需要重新筛选排列该数组, // 根据每个对象中 list的对象将有前后关系的对象归类, // 造出一个新数组对象; // list中对象是拥有先后顺序 ,且list中的用outerId来记录属于原来外层的id; 处理完成后的数组如下: [ { id: 1, list: [ { preId: '', nextId: '', id: 'N1', outerId: 1 } ] }, { id: 3, list: [ { preId: '', nextId: 'N6', id: 'N3', outerId: 3 }, { preId: 'N3', nextId: 'N4', id: 'N6', outerId: 6 }, { preId: 'N6', nextId: 'N2', id: 'N4', outerId: 4 }, { preId: 'N4', nextId: '', id: 'N2', outerId: 2 } ] }, { id: 5, list: [ { preId: '', nextId: '', id: 'N5', outerId: 5 } ] } ]; 处理完成后的数组中,每个元素代表原数组中的一个元素,其中包含一个 list 数组,list 数组中的元素代表原数组中与该元素有前后关系的元素。同时,每个 list 中的对象都记录了 outerId 属性,即属于原数组中的哪个对象。根据 preId 和 nextId 属性,可以将原数组中的元素归类到不同的 list 中。最终得到的新数组中,每个元素的 id 属性保持不变,仅在 list 中的对象中添加 outerId 属性。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/otMS 著作权归作者所有。请勿转载和采集!