Skip to content Skip to sidebar Skip to footer

Change Position Of Object Properties By Matching Other Array

I have an Object var $data = { D_1_AA_Changes.xml: 'This is a string', D_2_Compare_AA_Changes.xml: 'This is a string' } I need to match the property with another array I have

Solution 1:

It is possible to do this in a fully-compliant ES2015+ JavaScript engine, but in general, it's best to treat object properties as being unordered, since many object property operations (like for-in), even in ES2015+, are not guaranteed to follow the order that is used by the new ones (like Object.getOwnPropertyNames, JSON.stringify). Order is also not necessarily maintained when you serialize and deserialize (for instance, going to and from JSON). It may be, but it isn't guaranteed to be.* Relying on unguaranteed behavior leads to subtle, time-wasting bugs.

But if you want to do it on an ES2015+ engine, create a new object and add those properties in the order you want them to be in:

const $data = {
  "D_1_AA_Changes.xml": "This is a string",
  "D_2_Compare_AA_Changes.xml": "This is a string"
};

var list_match = ["D_2_Compare_AA_Changes","D_1_AA_Changes"];

console.log("before", JSON.stringify($data));

const $newData = {};
for (const entry of list_match) {
  const name = entry + ".xml";
  $newData[name] = $data[name];
}

console.log("after", JSON.stringify($newData));

Note that it works in this case because the property names don't look like array indexes, and these are "own" properties. Property names that look like array indexes aren't listed in creation order like other property names are.

So again: Strongly recommend not trying to use object property order.

More reading:


* JSON.stringify is guaranteed to follow the order, but the consumers of that JSON are not, necessarily.

Solution 2:

You can use the order in the array to access the object properties like so

list_match.forEach(function(key) {
  var myData = $data[key];
  /* you can check that `myData` is not undefined */
})

Post a Comment for "Change Position Of Object Properties By Matching Other Array"