Languages
[Edit]
EN

JavaScript - get random property from object

15 points
Created by:
JoanneSenior
980

In this article, we would like to show you how to get random property from object in JavaScript.

Practical example

In the below example, we use:

  • Object.keys() method to get the object keys as an array,
  • keys.length * Math.random() with Math.floor() to get a random key index within the range of the object keys number.

Runnable example:

// ONLINE-RUNNER:browser;

const randomProperty = (object) => {
    const keys = Object.keys(object);
    if (keys.length > 0) {
        const index = Math.floor(keys.length * Math.random());
      	const key = keys[index];
        const value = object[key];
        return {index, key, value}
    }
    return null;
};


// Usage example:

const object = {
    a: '1',
    b: '2',
    c: '3',
};

const property = randomProperty(object);

console.log(`key:   ${property.key}  `);
console.log(`value: ${property.value}`);

 

Random property name

// ONLINE-RUNNER:browser;

const randomPropertyName = (object) => {
    const keys = Object.keys(object);
    if (keys.length > 0) {
        const index = Math.floor(keys.length * Math.random());
      	return keys[index];
    }
    return null;
};


// Usage example:

const object = {
    a: '1',
    b: '2',
    c: '3',
};

console.log(randomPropertyName(object));

Random property value

// ONLINE-RUNNER:browser;

const randomPropertyValue = (object) => {
    const keys = Object.keys(object);
    if (keys.length > 0) {
        const index = Math.floor(keys.length * Math.random());
      	return object[keys[index]];
    }
    return null;
};


// Usage example:

const object = {
    a: '1',
    b: '2',
    c: '3',
};

console.log(randomPropertyValue(object));

 

See also

  1. JavaScript - random element from stream of elements

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join