0

I have a javascript object like:

{
  a: 3,
  b: 10,
  c: 2,
  d: 7,
}

I have an array containing string representations of the property names:

[ "c", "b", "a", "d" ]

How do I rearrange my object so that the properties are arranged in the same order as in the array, eg:

{
  c: 2,
  b: 10,
  a: 3,
  d: 7,
}
karel
  • 3,880
  • 31
  • 37
  • 42
tnoel999888
  • 407
  • 2
  • 10
  • 24
  • 1
    The order of properties in an Object is arbitrary. What is the actual goal here? – Chris G Aug 01 '19 at 13:49
  • 4
    You have to construct a new object and add the properties in the order you want. However I would strongly suggest you re-think the coding strategy that relies on object property ordering, because it will make your code extremely fragile. – Pointy Aug 01 '19 at 13:49
  • Can you sort the array to match the object property order? – jalynn2 Aug 01 '19 at 13:50
  • 1
    why not take the array as an ordered accessor? – Nina Scholz Aug 01 '19 at 13:51
  • 1
    This really seems like an [XY Problem](http://xyproblem.info/). What is your actual use case? – charlietfl Aug 01 '19 at 13:53
  • @ChrisG—not entirely, see [*Does ES6 introduce a well-defined order of enumeration for object properties?*](https://stackoverflow.com/questions/30076219/does-es6-introduce-a-well-defined-order-of-enumeration-for-object-properties) – RobG Aug 01 '19 at 14:14

1 Answers1

1

Although ECMAScript-6 improved the feature, object properties are still notoriously unordered. A way to fix this would be to use a Map which remembers the original key insertion order.

    const obj = { a: 3, b: 10, c: 2, d: 7 };
const arr = ["c", "b", "a", "d"];

const res = new Map(arr.map(e => [e, obj[e]]));

for (let [key, value] of [...res]) {
  console.log(key, value);
}

(The for...of loop is just to show the actual Map, as they aren't shown on the Stack Snippets console.)

Jack Bashford
  • 38,499
  • 10
  • 36
  • 67