EN
JavaScript - get object property by path
12
points
In this article, we would like to show you how to get object property by path in JavaScript.
In the below example, we create a function that takes two arguments:
object
we are working on,path
to the property in the object (delimited by '.
').
With the function, we can get an object's property value for the indicated path.
Practical example
// ONLINE-RUNNER:browser;
const getObjectProperty = (object, path) => {
if (object == null) { // null or undefined
return object;
}
const parts = path.split('.');
for (const key of parts) {
object = object[key];
if (object == null) { // null or undefined
return object;
}
}
return object;
};
// Usage example:
const data = {
user: {
username: 'john',
password: 'Secret$$'
},
rapot: {
title: 'Storage usage report',
goal: 'Remove unused data.'
}
};
console.log(getObjectProperty(data, 'user.username')); // john
console.log(getObjectProperty(data, 'user.password')); // Secret$$
console.log(getObjectProperty(data, 'rapot.title')); // Storage usage report
console.log(getObjectProperty(data, 'rapot.goal')); // Remove unused data.
Array
reduce()
based solution
// ONLINE-RUNNER:browser;
const getObjectProperty = (object, path) => {
if (object == null) { // null or undefined
return object;
}
const parts = path.split('.');
return parts.reduce((object, key) => object?.[key], object);
};
// Usage example:
const data = {
user: {
username: 'john',
password: 'Secret$$'
},
rapot: {
title: 'Storage usage report',
goal: 'Remove unused data.'
}
};
console.log(getObjectProperty(data, 'user.username')); // john
console.log(getObjectProperty(data, 'user.password')); // Secret$$
console.log(getObjectProperty(data, 'rapot.title')); // Storage usage report
console.log(getObjectProperty(data, 'rapot.goal')); // Remove unused data.