EN
JavaScript - set a value of nested key string descriptor inside an object
2 points
In this article, we would like to show how to sets a value of nested key string descriptor inside an object using modern ECMA Script (modern JavaScript).
Example solution:
xxxxxxxxxx
1
const setNestedProperty = (object, path, value) => {
2
if (path.length == 0) {
3
return;
4
}
5
const limit = path.length - 1;
6
for (let i = 0; i < limit; ++i) {
7
const name = path[i];
8
object = object[name] || (object[name] = { });
9
}
10
const name = path[limit];
11
object[name] = value;
12
}
13
14
// Usage example:
15
16
const object = {
17
name: 'John',
18
metadata: {
19
type: 'json'
20
}
21
};
22
const myKeyPath = ['metadata', 'key'];
23
const myKeyValue = 'my-key-value';
24
25
setNestedProperty(object, myKeyPath, myKeyValue);
26
console.log(`object.metadata.key='${object.metadata.key}'`);