为了账号安全,请及时绑定邮箱和手机立即绑定

在类型脚本和角度中对父项和子项进行排序

在类型脚本和角度中对父项和子项进行排序

慕桂英3389331 2022-09-29 16:47:11
我有这个列表:0: {id: 7, name: "333", code: "333", type: 3, hasParent: true, parentId: 4}1: {id: 6, name: "dfgdfg", code: "dfgdfg", type: 3, hasParent: false, parentId: null}2: {id: 5, name: "111", code: "111", type: 3, hasParent: true, parentId: 4}3: {id: 4, name: "22", code: "22", type: 1, hasParent: false, parentId: null}4: {id: 3, name: "yyy", code: "yyyy", type: 2, hasParent: false, parentId: null}5: {id: 2, name: "dfgdfg", code: "dfgdfg", type: 3, hasParent: true, parentId: 1}6: {id: 1, name: "cbcvb", code: "cvbcvcbv", type: 2, hasParent: false, parentId: null}我需要按父级和子级对此列表进行排序。如果项目的父值等于另一个项目的 id 的值,则应将具有 parentId 值的项目放在父值等于 id 值的项目下。喜欢这个列表:4: {id: 3, name: "yyy", code: "yyyy", type: 2, hasParent: false, parentId: 6}1: {id: 6, name: "dfgdfg", code: "dfgdfg", type: 3, hasParent: false, parentId: null}0: {id: 7, name: "333", code: "333", type: 3, hasParent: true, parentId: 4}2: {id: 5, name: "111", code: "111", type: 3, hasParent: true, parentId: 4}3: {id: 4, name: "22", code: "22", type: 1, hasParent: false, parentId: null}5: {id: 2, name: "dfgdfg", code: "dfgdfg", type: 3, hasParent: true, parentId: 1}6: {id: 1, name: "cbcvb", code: "cvbcvcbv", type: 2, hasParent: false, parentId: null}我写了这段代码,但它不起作用,没有对项目列表进行排序:    var Data = [{ id: 7, name: "333", code: "333", type: 3, hasParent: true, parentId: 4 },{ id: 6, name: "dfgdfg", code: "dfgdfg", type: 3, hasParent: false, parentId: null },{ id: 5, name: "111", code: "111", type: 3, hasParent: true, parentId: 4 },{ id: 4, name: "22", code: "22", type: 1, hasParent: false, parentId: null },{ id: 3, name: "yyy", code: "yyyy", type: 2, hasParent: false, parentId: null },{ id: 2, name: "dfgdfg", code: "dfgdfg", type: 3, hasParent: true, parentId: 1 },{ id: 1, name: "cbcvb", code: "cvbcvcbv", type: 2, hasParent: false, parentId: null }];问题出在哪里?我怎么能解决这个问题 ????
查看完整描述

1 回答

?
慕娘9325324

TA贡献1783条经验 获得超4个赞

如果它没有嵌套元素,我认为你可以做一些类似的事情(但不会给你相同的结果 - 真的我认为你有一个错误,parentId的3不是6?


this.sorted=[];

//get all the elements that has parent

const childs=this.data.filter(x=>x.parentId).sort((a,b)=>a.parentId-b.parentId)


//for each

childs.forEach((x,i)=>{

  this.sorted.push(x)     //<--add to sorted

                          //if is the last or the next has diferent parent

  if (i==childs.length-1 || childs[i+1].parentId!=x.parentId)

     this.sorted.push(this.data.find(p=>p.id==x.parentId)) //<--add the parent


})

//finally include the elements that is not in the list

this.data.forEach(x=>{

  if (!this.sorted.find(s=>s.id==x.id))

    this.sorted.push(x)

})


查看完整回答
反对 回复 2022-09-29
  • 1 回答
  • 0 关注
  • 57 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号