Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to shuffle elements within an object in JavaScript?

I have this object:

{ foo: 1, bar: 2, cheese: 3 }

I want to shuffle the elements, so it becomes:

{ bar: 2, cheese: 3, foo: 1 }

Or some other kind of combination. Is there a function to do this? This is because I want to produce varying results when using JSON.stringify on it. The only answers I could find on the internet refer to shuffling objects within an array.

Thanks.

like image 761
Lucas Avatar asked Apr 29 '14 07:04

Lucas


3 Answers

JS object properties have no intrinsic order. Most JS runtimes preserve the ordering that the keys were added in, but that is not a language requirement and you should not rely on it. For example, it would be perfectly valid for JSON.stringify to just always serialize keys in alphabetical order or randomize them.

If the ordering is important, you could potentially keep a set of two arrays to track the keys and values.

like image 154
loganfsmyth Avatar answered Nov 15 '22 11:11

loganfsmyth


Object properties (as of 2014) do NOT have a defined order and there is no language support for defining or changing the order of the properties. Per the language specification, order does not have to be preserved in any way.

If you want a defined order, you should use an Array.

like image 44
jfriend00 Avatar answered Nov 15 '22 10:11

jfriend00


To randomize the order of properties in an object you can access the keys, shuffle them, then assemble a new object. Here's a function:

let obj = { "a":1, "b":2, "c":3, "d":4 }

function shuffleObject(obj){
    // new obj to return
  let newObj = {};
    // create keys array
  var keys = Object.keys(obj);
    // randomize keys array
    keys.sort(function(a,b){return Math.random()- 0.5;});
  // save in new array
    keys.forEach(function(k) {
        newObj[k] = obj[k];
});
  return newObj;
}

console.log(shuffleObject(obj));
console.log(shuffleObject(obj));
console.log(shuffleObject(obj));
like image 4
ow3n Avatar answered Nov 15 '22 09:11

ow3n