Properties have no order, but this trick worked for me (lodash required) :
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function shuffleObject(obj) {
// Get object key into tmp array in random order
var keys = this.shuffle(_.keys(obj));
// instantiate new object who will be returned
var newObj = {};
// Iterate over keys to populate object with same properties in a different order
keys.forEach(function(elm, index){
newObj[elm] = obj[elm];
if(index === keys.length-1){
return newObj;
}
})
}
console.log(shuffleObject({ "A": 1, "B": 2, "C": 3, "D": 4 });
//{ "B": 2, "C": 3, "D": 4,"A": 1 }