繁体   English   中英

将数组转换为 object 而不对 javascript 中的键进行排序

[英]Convert array to object without sorting keys in javascript

我有一个 object

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

这可能吗?

我尝试将其转换为数组,然后转换为 object 但新的 object 以密钥 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}
}

编辑

值得一提的是,我的 object 是键入的:

顺便说一句, this.props.items的类型为TypeScript object 例如。 Section.Item[]

您可以获取键和值并将弹出的值分配给键。

 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);

你可以使用fromEntries

 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]) ) );

也许你可以试试这个

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM