gpt4 book ai didi

javascript - 对嵌套对象排序

转载 作者:行者123 更新时间:2023-11-29 23:07:43 25 4
gpt4 key购买 nike

我正在尝试通过 object.keys 在 cummulativeSite 的基础上按降序对 javascript 中的对象 obj 对象进行排序,但它没有得到排序。请提出一个好的方法或相同的方法来对此进行排序。

var obj={


B.E:{
A: {percentgsite: 8.5, backlogenclsite: 8.5, regularenclsite: 3.5, cummulativeSite: 20.5},
B: {percentgsite: 5.9, backlogenclsite: 5.9, regularenclsite: 8.5, cummulativeSite: 20.3},
C: {percentgsite: 5.9, backlogenclsite: 6.4, regularenclsite: 8.9, cummulativeSite: 21.200000000000003}
},



Diploma:{
A: {percentgsite: 8.5, cummulativeSite: 5.2},
B: {percentgsite: 5.9, cummulativeSite: 8.5},
C: {percentgsite: 5.9, cummulativeSite: 5.6}
},



M.E:{
A: {percentgsite: 8.5, cummulativeSite: 11.9},
B: {percentgsite: 5.9, cummulativeSite: 12.9},
C: {percentgsite: 5.9, cummulativeSite: 13.5}
}
}

预期输出:

var obj={


B.E:{

C: {percentgsite: 5.9, backlogenclsite: 6.4, regularenclsite: 8.9, cummulativeSite: 21.200000000000003},
A: {percentgsite: 8.5, backlogenclsite: 8.5, regularenclsite: 3.5, cummulativeSite: 20.5},
B: {percentgsite: 5.9, backlogenclsite: 5.9, regularenclsite: 8.5, cummulativeSite: 20.3}
},



Diploma:{
B: {percentgsite: 8.5, cummulativeSite: 8.5},
C: {percentgsite: 5.9, cummulativeSite: 5.6},
A: {percentgsite: 5.9, cummulativeSite: 5.2}
},



M.E:{
C: {percentgsite: 8.5, cummulativeSite: 13.5},
B: {percentgsite: 5.9, cummulativeSite: 12.9},
A: {percentgsite: 5.9, cummulativeSite: 11.9}
}
}

最佳答案

正如您在评论中提到的,您可以将 B.E 等更改为数组(因为对象不保证顺序)。所以我将在数组中更改它们,而不是根据 cummulativeSite 属性对它们进行排序

var obj={'B.E':[{A:{percentgsite:8.5,backlogenclsite:8.5,regularenclsite:3.5,cummulativeSite:20.5}},{B:{percentgsite:5.9,backlogenclsite:5.9,regularenclsite:8.5,cummulativeSite:20.3}},{C:{percentgsite:5.9,backlogenclsite:6.4,regularenclsite:8.9,cummulativeSite:21.200000000000003}}],Diploma:[{A:{percentgsite:8.5,cummulativeSite:5.2}},{B:{percentgsite:5.9,cummulativeSite:8.5}},{C:{percentgsite:5.9,cummulativeSite:5.6}}],'M.E':[{A:{percentgsite:8.5,cummulativeSite:11.9}},{B:{percentgsite:5.9,cummulativeSite:12.9}},{C:{percentgsite:5.9,cummulativeSite:13.5}}]}

Object.keys(obj).forEach(e => {
obj[e].sort( (a,b) =>{
return Object.values(a)[0].cummulativeSite -
Object.values(b)[0].cummulativeSite
})
})

console.log(obj)

关于javascript - 对嵌套对象排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54478137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com