1

I have JSON object, which I want to sort it in certain way,

This is my object

{ "you": 100, "me": 75, "foo": 116, "bar": 15 }

And I want this object to be sorted in this order ['me', 'foo', 'you', 'bar'] which the object would become like this,

{ "me": 75, "foo": 116, "you": 100, "bar": 15 }

Is there anyway to achieve this ?

Venkat
  • 255
  • 1
  • 13
  • 2
    Object properties have no ordering. You can extract the keys with `Object.keys()`, sort that array, and then use the array to get property values in some particular order. – Pointy Nov 28 '17 at 13:59
  • If you already have an order defined with `['me', 'foo', 'you', 'bar']`, then why do you need to sort the object also? You can always fetch the properties in the order of the array you have defined. – gurvinder372 Nov 28 '17 at 14:01

1 Answers1

2

You could build a new object by iterating the given array with the keys.

More about order of objects: Does JavaScript Guarantee Object Property Order?

var object = { you: 100, me: 75, foo: 116, bar: 15 },
    result = Object.assign(...['me', 'foo', 'you', 'bar'].map(k => ({ [k]: object[k] })));

console.log(result);
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
  • 1
    This will be messed up a property name is numeric.. `var object = { you: 100, me: 75, foo: 116, bar: 15, 1 : 23, "2" : 2 }, result = Object.assign(...['me', 'foo', 'you', 'bar', "2"].map(k => ({ [k]: object[k] }))); console.log(result);` – gurvinder372 Nov 28 '17 at 14:03
  • @gurvinder372, the order is defined by keys who are possible to parse as integer are sorted first by value and then comes the rest with in insertation order. you may have a look into newer ecmascript standard. – Nina Scholz Nov 28 '17 at 14:05