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.
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.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With