Javascript appending object doesn't guarantee order

前端 未结 3 1996
暖寄归人
暖寄归人 2021-01-16 02:54

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

some says they guarantee, some s

相关标签:
3条回答
  • 2021-01-16 03:17

    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)

    0 讨论(0)
  • 2021-01-16 03:36

    A simpler bit of code would be like this (use a for loop instead of forEach:

    let newObj = {};
    for (const data of arrayObject) {
      newObj[data.id] = data;
    }
    

    This might get you what you want because it will guarantee that the order the object is built matches the order in the array. Using forEach causes multiple functions to be called in whatever order they run, which might be out of order. But realize that even using the for-loop does not guarantee the order will always match. An Array will guarantee the order, but the Object made this way does not. Even if the above code does give you the desired order, it might not in the future. Use an Array if you need to preserve order.

    0 讨论(0)
  • 2021-01-16 03:38

    I think what you're looking for is a Map() object. See here -> Map and Set

    const arrayObject = [
      {id:'a123', bar:'hello'}, 
      {id:'a321', bar: 'foo'},
      {id:'a234', bar: 'more'},
      {id:'a735', bar: 'words'},
      {id:'a167', bar: 'added'},
      {id:'a857', bar: 'now'},
    ];
    
    var newObj = new Map();
    
    for (var i=0; i<arrayObject.length; i++) {
      const temp = {
            id: arrayObject[i].id,
            bar: arrayObject[i].bar
       };
       newObj.set(arrayObject[i].id, temp);
    }
    
    var jsonText = JSON.stringify(Array.from(newObj.entries()));
    
    console.log(jsonText);
    
    // To get at the elements, use .get()
    
    console.log(newObj.get("a321").bar);

    0 讨论(0)
提交回复
热议问题