Skip to content

Instantly share code, notes, and snippets.

@IrakliJani
Created May 31, 2014 11:58
Show Gist options
  • Save IrakliJani/10596e8f2f6e963e8e88 to your computer and use it in GitHub Desktop.
Save IrakliJani/10596e8f2f6e963e8e88 to your computer and use it in GitHub Desktop.
Object.prototype.random = function() {
return this.toRandomArray()[0];
};
Object.prototype.toRandomArray = function() {
function object_values(object, values) {
Object.keys(object).forEach(function (key) {
typeof object[key] === 'object'
? object_values(object[key], values)
: values.push(object[key]);
});
return values;
}
return object_values(this, []).sort(function() {
return 0.5 - Math.random();
});
};
var obj = {
a: 1,
b: {
x: 2,
y: 3
},
c: {
z: {
q: 4
}
}
};
console.log(obj.toRandomArray());
console.log(obj.random());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment