【发布时间】:2020-08-16 01:52:00
【问题描述】:
我有一个对象
{
1: {id: 1, first: 1, last: 5}
2: {id: 2, first: 6, last: 10}
3: {id: 3, first: 11, last: 15}
}
我需要颠倒项目顺序而不对键进行排序,所以最终结果是:
{
1: {id: 3, first: 11, last: 15}
2: {id: 2, first: 6, last: 10}
3: {id: 1, first: 1, last: 5}
}
这可能吗?
我尝试将其转换为数组,然后转换为对象,但新对象以键 0 开头,而我需要它以键 1 开头:
let array = [];
Object.values(this.props.items)
.sort()
.reverse()
.forEach(function(b) {
array.push(b);
});
const newItems = Object.assign({}, array);
// Result:
{
0: {id: 3, first: 11, last: 15}
1: {id: 2, first: 6, last: 10}
2: {id: 1, first: 1, last: 5}
}
编辑
值得一提的是我的对象是键入的:
顺便说一句,this.props.items 被键入 TypeScript 对象,例如。 Section.Item[]
【问题讨论】:
-
let array = [{}];从位置 0 的元素开始,然后是delete newItems[0];。 -
@palaѕн N.B.这个 OP 想要随机排列哪些值存储在键
1、2和3下,而不是对键本身进行排序。
标签: javascript reactjs typescript sorting javascript-objects