0

I want to shuffle objects inside an object and I found this code, but unfortunately it doesn't work and I get the same order as the object is written!

How can I get shuffled result?

const obj = {

    0: {

        expands: [0],

    },

    1: {

        expands: [1],

    },

    2: {

        reference: "Have you ever* looked* us",

    },

};

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));
Sara Ree
  • 3,417
  • 12
  • 48
  • 1
    Numeric keys are always kept in numeric order. Use an array if you need to change the order. – Barmar Sep 08 '20 at 16:11
  • Also see: https://www.stefanjudis.com/today-i-learned/property-order-is-predictable-in-javascript-objects-since-es2015/#1-integer-indices. Basically, if a key can be evaluated as an integer, it will be treated as such and will be sorted numerically regardless of the insertion order. – Terry Sep 08 '20 at 16:13
  • Numeric keys in a object always kept in order in a object! I thought there are no orders for a object keys!!! – Sara Ree Sep 08 '20 at 16:13
  • If you thought there was no order for object keys, why did you think this would work? – Heretic Monkey Sep 08 '20 at 16:14
  • Seems like you are treating an object as an array, so is here a reason you are not using an array? – epascarello Sep 08 '20 at 16:16
  • There is one way to do this I think... I should rename the keys inside the main object randomly... – Sara Ree Sep 08 '20 at 16:19

0 Answers0