在javascript中转换数组为对象而不进行键值排序

问题描述 投票:0回答:1

我有一个对象

{
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}
}

EDIT

值得一提的是,我的对象是类型化的。

Btw this.props.items 被打成 TypeScript 对象例如 Section.Item[]

javascript reactjs sorting javascript-objects
1个回答
1
投票

你可以使用 从条目

const data = {
  1: { id: 1, first: 1, last: 5 },
  2: { id: 2, first: 6, last: 10 },
  3: { id: 3, first: 11, last: 15 },
};
console.log(
  Object.fromEntries(
    Object.values(data)
      .reverse()
      .map((val, index) => [index + 1, val])
  )
);

2
投票

你可以得到键和值,并将弹出的值赋给键。

var object = { 1: { id: 1, first: 1, last: 5 }, 2: { id: 2, first: 6, last: 10 }, 3: { id: 3, first: 11, last: 15 } },
    values = Object.values(object)

Object.keys(object).forEach(k => object[k] = values.pop());

console.log(object);

0
投票

也许你可以试试这个

let obj = {
  1: {id: 1, first: 1, last: 5},
  2: {id: 2, first: 6, last: 10},
  3: {id: 3, first: 11, last: 15}
}

const newItems = {}
let totalKeys = Object.keys(obj).length

for (let key in obj) {
  newItems[totalKeys] = obj[key];

  totalKeys -= 1;
}

console.log(newItems);
© www.soinside.com 2019 - 2024. All rights reserved.