Languages
[Edit]
EN

JavaScript - set object property by path

7 points
Created by:
Dirask Community
3960

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

In below example, we create a function that takes three arguments:

  • object┬áthat we modify,
  • path to the property in the object (delimited by '.'),
  • value that is set under the specified path.

With the function, we can create new object properties and specify their value or override existing ones.

Runnable example:

// ONLINE-RUNNER:browser;

const setObjectProperty = (object, path, value) => {
  	const parts = path.split('.');
  	const limit = parts.length - 1;
	for (let i = 0; i < limit; ++i) {
      	const key = parts[i];
    	object = object[key] ?? (object[key] = { });
    }
  	const key = parts[limit];
    object[key] = value;
};

// Usage example:

const data = { };

setObjectProperty(data, 'user.username', 'john');
setObjectProperty(data, 'user.password', 'Secret$$');
setObjectProperty(data, 'rapot.title', 'Storage usage raport');
setObjectProperty(data, 'rapot.goal', 'Remove unused data.');

console.log(JSON.stringify(data, null, 4));
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