JavaScript附加对象不能保证顺序 [英] Javascript appending object doesn't guarantee order

查看:87
本文介绍了JavaScript附加对象不能保证顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在堆栈溢出中研究了有关对象保证顺序的问题。
JavaScript是否保证对象属性顺序?

I have looked at this question in stack overflow about objects guaranteeing order. Does JavaScript Guarantee Object Property Order?

根据情况,有些人保证,有些则不保证。同时,我遇到了以下问题。

some says they guarantee, some says they don't, depending on situations. Meantime I've encountered following problem.

我有一个对象数组,如下所示:

I have an array of objects, similar to below:

const arrayObject = [
{id:'a123', bar:'hello'}, 
{id:'a321', bar: 'foo'} ];

现在我希望将此arrayObject转换为object的对象,其结构如下,其顺序与数组:

now I wish to turn this arrayObject into object of object, with structure as follows with the same order as the array:

const object = {
   'a123': {id:'a123', bar:'hello'},
   'a321': {id:'a321', bar: 'foo'},
}

主要使用数组中每个项目的ID作为对象的键。下面是我用来尝试实现的代码:

basically using the id of each item in the array as the key of the object. Below is the code I used to try to achieve it:

let newObj = {};
arrayObject.forEach(data=>{
   const temp = {
     [data.id]:{
        id: data.id,
        bar: data.bar
     },
   };
   newObj={...newObj, ...temp};
})

我确实获得了正确的结构,但是顺序与arrayObject的顺序不同,即返回:

I do get the correct structure, however the order is not the same as the order of arrayObject, i.e. it returns:

const object = {
   'a321': {id:'a321', bar: 'foo'},
   'a123': {id:'a123', bar:'hello'},
}

我尝试了数组中的更多项目,但得到的结果相同。它不保证订单。

I've tried with more items in the array, and I get same result. It does not guarantee the order.

我的代码是否有问题,还是只是不保证订单顺序?

Is there something wrong with my code, or is it simply not guaranteeing the order?

我该怎么做才能使对象与数组的顺序相同?

What do I have to do to make the object be the same order as the array?

推荐答案

通过在(无序)对象中包含订购信息来保留订单。以后任何时候,当您需要恢复原始订单时,请使用保存的订购信息...

Preserve the order by including ordering information in the (unordered) object. Anytime later, when you need to recover the original order, use the saved ordering information...

const arrayObject = [{
    id: 'a123',
    bar: 'hello'
  },
  {
    id: 'a321',
    bar: 'foo'
  }
];

let object = {}
arrayObject.forEach((e, i) => {
  object[e.id] = { ...e, orderWith: i } // the index will tell us how to sort later
})

// later on
let sorted = Object.values(object).sort((a, b) => a.orderWith - b.orderWith)
console.log(sorted)

这篇关于JavaScript附加对象不能保证顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆