Sohail
Sohail

Reputation: 597

How to rearrange attributes of an object?

I have an object like this:

user = {
  'a': 0,
  'b': 1,
  'c': 3,
  'd': 4
}

I want to rearrange its properties like this:

user = {
  'c': 3,
  'a': 0,
  'b': 1,
  'd': 4
}

I don't want to create a new object instead I want to rearrange the attributes of the existing object.

Upvotes: 1

Views: 1251

Answers (2)

Davi
Davi

Reputation: 4147

You cannot define the order of keys in a normal object. What you can do instead is to transform the Object into a Map.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

A Map object iterates its elements in insertion order — a for...of loop returns an array of [key, value] for each iteration.

var user = {a: 0, b: 1, c: 3, d: 4};
var uMap = new Map([['c', user.c], ['a', user.a], ['b', user.b], ['d', user.d]]);

Or, you can turn your Object into an Array and work with it. The downside of this approach is that you have to remember the correct index position of the properties/what property corresponds to which position in the array:

var user = {a: 0, b: 1, c: 3, d: 4};
var uArr = [user.c, user.a, user.b, user.d];

Upvotes: 1

JonnyIrving
JonnyIrving

Reputation: 753

In a JavaScript object, you can't really order key/value pairs. They are stored in their own internal format and so the ordering can never really be relied upon.

I'm not sure what your exact use case is but if you need a guaranteed order of certain fields you could create an array that contains the field names in the order you require and use this to iterate through the object and fetch the values as you require.

Hope this helps!

Upvotes: 1

Related Questions