简体   繁体   中英

Changing Deeply Nested Object Value

This seems to be obvious, but i can't figure out how to shortening change deeply nested object value in multiple places in the code without retyping each time keys path to this value:

> obj = { 'key1': { 'key2': { 'key3': { 'key4': { 'key5': 'value' }}}}}
> obj.key1.key2.key3.key4.key5
'value'

> obj.key1.key2.key3.key4.key5 = 'changeme'
> obj.key1.key2.key3.key4.key5
'changeme'

> obj.key1.key2.key3.key4.key5 = 'changeme2'
> obj.key1.key2.key3.key4.key5
'changeme2'

You could assign the innermost object to a variable.

var foo = obj.key1.key2.key3.key4;

From there on out, accessing/modifying foo.key5 will be equivalent to accessing/modifying obj.key1.key2.key3.key4.key5 .

foo.key5 = 'new value'
console.log(obj.key1.key2.key3.key4.key5); // 'new value'

You could use a bit of recursion to iterate over every key in your object and update where it finds a matching key.

 const obj = { 'key1': { 'key2': { 'key3': { 'key4': { 'key5': 'value' }}}, 'key5': 'test'}} const mutateObjectProperty = (prop, value, obj) => obj.constructor === Object && Object.keys(obj).forEach(key => { if (key === prop) obj[key] = value mutateObjectProperty(prop, value, obj[key]) }) mutateObjectProperty('key5', 'updated', obj) console.log(obj) 

You can use JSON.stringify() , JSON.parse() , String.prototype.replace() . You can also use a RegExp that only checks property name, instead of both property name and value.

 var obj = { 'key1': { 'key2': { 'key3': { 'key4': { 'key5': 'value' }}}}} function updateObject(obj, key, val, value) { return JSON.parse(JSON.stringify(obj) .replace(new RegExp(`"${key}":"${val}"`), `"${key}":"${value}"`)) } obj = updateObject(obj, "key5", "value", "changeme"); console.log(obj); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM