Created
May 31, 2014 11:58
-
-
Save IrakliJani/10596e8f2f6e963e8e88 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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