我有下一个对象:
ctrl.items
此对象包含其他对象:
items: {
OBJ1: {
label: 'banana'
},
OBJ2: {
label: 'apple'
},
OBJ3: {
label: 'cat'
}
}
在 UI 中,我将项目下的每个对象的标签显示为列表的一部分。我希望此列表按字母顺序排序,因此列表将是:apple 香蕉猫
所以排序后我的预期对象应该是
items: {
OBJ1: {
label: 'apple'
},
OBJ2: {
label: 'banana'
},
OBJ3: {
label: 'cat'
}
}
我该怎么做?我尝试了各种排序示例,但没有任何效果。例如我试过:
ctrl.items.sort((a,b) => (a.label > b.label) ? 1 : ((b.label > a.label) ? -1 : 0));
items
是一个对象,而不是一个数组,所以你不能.sort
在它上面使用。
但是,您可以通过使用将对象转换为数组 Object.entries(items)
下面是一个例子:
let items = {
OBJ1: {
label: 'banana'
},
OBJ2: {
label: 'apple'
},
OBJ3: {
label: 'cat'
}
}
// to be used by `Array.sort()`
function compare(a, b) {
return a < b ? -1
: a > b ? 1
: 0
}
// convert from object to key-value pair array
let entries = Object.entries(items)
// take out the keys
let keys = entries.map(entry => entry[0])
// take out the values
let values = entries.map(entry=>entry[1])
// store the value by label
values.sort((a,b) => compare(a.label, b.label))
// rebuild the object from the original keys and sorted values
let result = Object.fromEntries((keys.map((key,i) => [key, values[i]])))
/*
result will be:
{
OBJ1: { label: 'apple' },
OBJ2: { label: 'banana' },
OBJ3: { label: 'cat' }
}
*/
- 添加
我不确定您为什么以要求的格式存储值。您也可以将值存储在数组中。这样你就可以直接对数组进行排序。
例如:
let labels = [ 'banana', 'apple', 'cat' ]
labels.sort()
// the labels is now [ 'apple', 'banana', 'cat' ]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句