0

So I want to change the content of object "alfa" according to a list of keyNames according to the newValue.

let alfa = { 
    bravo : { 
        charlie : { 
            delta : "echo" 
        } 
    } 
}

const newValue = { foxtrot : "golf" }

I want to do something like this, dynamically:

alfa[keyNames] = newValue

// where if

const keyNames = ["bravo", "charlie"]
// would do:
alfa["bravo"]["charlie"] = newValue

// or if 

const keyNames = ["bravo"]
// would do:
alfa["bravo"] = newValue

How to do that?

I know I can do this, but there is probably a way to cover every possibles cases...

if(keyNames.length === 1){ alfa[keyNames[0]] = newValue }
if(keyNames.length === 2){ alfa[keyNames[0]][keyNames[1]] = newValue }
...

2
  • Can you please elaborate more on what you mean by dynamically. Commented Jul 2, 2020 at 4:10
  • @HarryBomrah, yes, just did it. Commented Jul 2, 2020 at 4:25

1 Answer 1

1

it would be a setValue function.

const alfa = {};
const keyNames = ["bravo", "charlie"];

function setValue(target,keyPath,value){
  [target,...keyNames].reduce((object,keyName) => {
    if( keyName === keyPath[keyPath.length-1] ){
      object[keyName] = value;
    }

    object[keyName] = object[keyName] || {};
      return object[keyName]
    })
}

setValue(alfa,keyNames,"oboo")
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.