Pick a random property of an object
Return one of the object’s own enumerable keys.
function randomKey(object) { const keys = Object.keys(object); return keys[Math.floor(Math.random() * keys.length)]; }
Usage
const colors = { aqua: '#00ffff', azure: '#f0ffff', beige: '#f5f5dc' };
Object.hasOwn(colors, randomKey(colors)); // → true
randomKey({}); // → undefined
Know the limits
- Own enumerable string keys only; an empty object returns undefined. The original called Object.keys twice.
The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.
Source & maintenance
Based on Pick a random property of an object from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Generate a random boolean — Return true or false with equal probability.
- Generate a random floating point number in given range — Scale Math.random into [min, max).
- Generate a random hex color — Return a #rrggbb color from 24 random bits.