There is a string

var str = "key1.key2.key3"; 

There is an object

 var obj = { key1: { key2: { key3: false } } } 

You need to get to the key in obj.key1.key2.key3 from the keys indicated in the row through a dot and change the value to another.

Variant of the answer for old browsers:

 str = str.split("."); var strLng = str.length; var tmp = obj; for(var strIdx = 0; strIdx < strLng; strIdx++) { if(strIdx < strLng - 1) { tmp = tmp[str[strIdx]]; } else { tmp[str[strIdx]] = true; } } 

    2 answers 2

    one of the options -

     var str = "key1.key2.key3"; var obj = { key1: { key2: { key3: false } } } const getValueByPath = ( source, path ) => str.split('.').reduce( ( object, prop ) => object = object[ prop ] , source ); const setValueByPath = ( source, path, value ) => str.split('.').reduce( ( object, prop, index, array ) => { if( index < array.length - 1 ){ object = object[ prop ] }else{ object[ prop ] = value; } return object; } , source ); setValueByPath( obj, str, true ) console.log( getValueByPath( obj, str ) ); 

    And using recursion -

     var str = "key1.key2.key3"; var obj = { key1: { key2: { key3: false } } } const setValueByPath = ( object, keys, value ) => keys.length > 1 ? setValueByPath( object = object[ keys.shift() ], keys, value ) : object[ keys.shift() ] = value; const getValueByPath = ( object, keys ) => keys.length > 1 ? getValueByPath( object = object[ keys.shift() ], keys ) : object[ keys.shift() ]; let path = str.split('.'); setValueByPath( obj, [ ...path ], "new value" ); console.log( getValueByPath( obj, [ ...path ] ) ); 

    • I did not understand how to change the value in obj.key1.key2.key3 - bsbak

    You can use the loop to go through the object in the depth of the keys, to the penultimate. Then, having received the penultimate object, replace the value with the last key.

     function set_value( object, path, new_value ){ const names = path.split( '.' ); const last_key = names.pop(); const obj_before_last = 0 in names ? get_value( object, names.join('.') ) : object; obj_before_last[ last_key ] = new_value; return object } function get_value( object, path ){ const names = path.split( '.' ); let cur_obj = object; for( let i = 0; i < names.length; i++ ) cur_obj = cur_obj[ names[ i ] ]; return cur_obj; } //изменять так set_value( { a: { b: { c: false } } }, "abc", true ); //result {a:{b:{c:true}}} set_value( { a: 'foo' }, "a", 'boo' ); //result {a:'boo'} 

    Or you can use one of a dozen libraries in npm. For example, Peek or deep-property