Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript shuffling object properties with their values

Tags:

javascript

Hello everyone,

what I'd like to achieve is to shuffle all the object's properties including their values...

object:

    var numbers = { one : 1, two : 2, three : 3};

result:

     Object {two: 2, one: 1, three: 3} 

or any other variation

I have tried couple of array shuffle methods but none of them worked for me...

like image 537
Wracker Avatar asked Jun 11 '26 22:06

Wracker


1 Answers

As of ECMAScript 2015 (ES2015, aka ES6), object properties do have an order (they didn't before):

  1. Let keys be a new empty List.
  2. For each own property key P of O that is an integer index, in ascending numeric index order
    • Add P as the last element of keys.
  3. For each own property key P of O that is a String but is not an integer index, in property creation order
    • Add P as the last element of keys.
  4. For each own property key P of O that is a Symbol, in property creation order
    • Add P as the last element of keys.
  5. Return keys.

Consequently, it's now possible to do what you asked, by creating a new object and adding the properties to it in the order you want them to appear:

let numbers = { one : 1, two : 2, three : 3};
numbers = Object.keys(numbers)
    .map((key) => ({key, value: numbers[key]}))
    .sort((a, b) => b.key.localeCompare(a.key))
    .reduce((acc, e) => {
      acc[e.key] = e.value;
      return acc;
    }, {});
console.log(JSON.stringify(numbers));

Live Example

That's sorted, not shuffled, but instead of sort you can shuffle in any of several ways, as outlined in this question's answers.

That works on ES2015+ JavaScript engines. I'm not saying it (using property order this way) a worthwhile thing to do. :-)

You could argue that that's a bit of an abusage of reduce, but it let me keep it all to one big expression. (Which you could further argue is a silly thing for me to do. :-) )

like image 88
T.J. Crowder Avatar answered Jun 14 '26 11:06

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!