Languages
[Edit]
EN

JavaScript - get object property by path

12 points
Created by:
Dirask Community
3930

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

In 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.

Runnable example:

// ONLINE-RUNNER:browser;

const getObjectProperty = (object, path) => {
  	if (path === undefined || path === null) {
    	return object;
    }
  	const parts = path.split('.');
	for (let i = 0; i < parts.length; ++i) {
      	if (object === undefined || object === null) {
        	return undefined;
        }
      	const key = parts[i];
    	object = object[key];
    }
  	return object;
};

// Usage example:

const data = {
    user: {
        username: 'john',
        password: 'Secret$$'
    },
    rapot: {
        title: 'Storage usage raport',
        goal: 'Remove unused data.'
    }
};

console.log(getObjectProperty(data, 'user.username'));
console.log(getObjectProperty(data, 'user.password'));
console.log(getObjectProperty(data, 'rapot.title'));
console.log(getObjectProperty(data, 'rapot.goal'));

 Reduce method based solution

// ONLINE-RUNNER:browser;

const getObjectProperty = (data, path) => {
    if (path === undefined || path === null) {
    	return object;
    }
  	const parts = path.split('.');
    return parts.reduce((data, key) => data?.[key], data);
};

// Usage example:

const data = {
    user: {
        username: 'john',
        password: 'Secret$$'
    },
    rapot: {
        title: 'Storage usage raport',
        goal: 'Remove unused data.'
    }
};

console.log(getObjectProperty(data, 'user.username'));
console.log(getObjectProperty(data, 'user.password'));
console.log(getObjectProperty(data, 'rapot.title'));
console.log(getObjectProperty(data, 'rapot.goal'));

 

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