简体   繁体   中英

Preserving the object key value ordering when it is pushed into array

When elements in an object is ordered using filter and then pushed onto array it loses the ordering and uses alphabetical order of key how to preserve the ordering after inserting into array ?

  app.controller('MainCtrl', function($scope, $filter) {
    var bigArr = [];
    var arr = [
      {
          "Type1" : "Canada",
          "ColPos" : 3
      },
      {
          "Type2" : "UK",
          "ColPos" : 1
      },
      {
          "Type3" : "US",
          "ColPos" : 2
      },
      {
          "Type4" : "Madagascar",
          "ColPos" : 0
      },
  ]

  var ordered = $filter('orderBy')(arr,'ColPos');
  console.log(ordered);

  var obj =  _.assign.apply(_, ordered);
  console.log(obj)

  bigArr.push(obj);
  console.log(bigArr);  // ordering is lost
  });

Demo : http://plnkr.co/edit/sgFDVRrbrIXg2drUZzL3?p=preview

Ordering is lost because it doesn't really exist, in fact ES5 does specify that object keys aren't ordered in a special way and is browser's implementation dependent as stated here :

The mechanics and order of enumerating the properties (step 6.a in the first algorithm, step 7.a in the second) is not specified.

Short answer: you can't rely on this structure to do this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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