EN
JavaScript - get random property from object
15 points
In this article, we would like to show you how to get random property from object in JavaScript.
In the below example, we use:
Object.keys()
method to get the object keys as an array,keys.length * Math.random()
withMath.floor()
to get a random key index within the range of the object keys number.
Runnable example:
xxxxxxxxxx
1
const randomProperty = (object) => {
2
const keys = Object.keys(object);
3
if (keys.length > 0) {
4
const index = Math.floor(keys.length * Math.random());
5
const key = keys[index];
6
const value = object[key];
7
return {index, key, value}
8
}
9
return null;
10
};
11
12
13
// Usage example:
14
15
const object = {
16
a: '1',
17
b: '2',
18
c: '3',
19
};
20
21
const property = randomProperty(object);
22
23
console.log(`key: ${property.key} `);
24
console.log(`value: ${property.value}`);
xxxxxxxxxx
1
const randomPropertyName = (object) => {
2
const keys = Object.keys(object);
3
if (keys.length > 0) {
4
const index = Math.floor(keys.length * Math.random());
5
return keys[index];
6
}
7
return null;
8
};
9
10
11
// Usage example:
12
13
const object = {
14
a: '1',
15
b: '2',
16
c: '3',
17
};
18
19
console.log(randomPropertyName(object));
xxxxxxxxxx
1
const randomPropertyValue = (object) => {
2
const keys = Object.keys(object);
3
if (keys.length > 0) {
4
const index = Math.floor(keys.length * Math.random());
5
return object[keys[index]];
6
}
7
return null;
8
};
9
10
11
// Usage example:
12
13
const object = {
14
a: '1',
15
b: '2',
16
c: '3',
17
};
18
19
console.log(randomPropertyValue(object));