我有一个带有ID的子对象的对象。我想通过特定属性对子对象进行排序,但又不要丢失id引用。
我已经尝试过使用lodash和我发现的不同Vanilla js解决方案按位置分别对子对象“选项”进行排序,然后将其重新分配给主对象,但是我松散了id,因为在所有情况下它都返回一个数组,我可以找不到保持相同ID结构的方法。
对象示例:
{
name: 'User name',
options: {
'234aafg': {
name: 'bar',
position: 2
},
'543al22': {
name: 'foo',
position: 0
},
'437uaz2': {
name: 'baz',
position: 1
},
}
}
预期结果:
{
name: 'User name',
options: {
'543al22': {
name: 'foo',
position: 0
},
'437uaz2': {
name: 'baz',
position: 1
},
'234aafg': {
name: 'bar',
position: 2
}
}
}
obj.options.sort((a,b) => {
if(a.poistion<b.position) return -1
return 1
})