Is it possible to shuffle elements inside 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 combination. Is there a function for this? This is due to the fact that I want to get different results when used JSON.stringifyon it. The only answers I could find on the Internet are about shuffling objects inside an array.

Thank.

+4
source share
5 answers

JS . JS , , . , JSON.stringify .

, .

+7

. .

, .

+7

Shuffle?

function shuffle(o){ //v1.0
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};

shuffle (myArray)

...

0

, ( lodash):

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 }
0

To randomize the order of properties of an object, you can access the keys, shuffle them, and then assemble a new object. Here's the 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));
Run code
0
source

Source: https://habr.com/ru/post/1538531/


All Articles