1

I have a player object with sub property type:

'player': {
            'count': 11,
            'type': 'forward'
}

Now i would like to call setPlayer( {...playerDetails, [key]: e.target.value}) to keep the existing player object and only change one property (i.e. player.type).

Using [key]: e.target.value works fine with changing root level property like player , but how can i use key to set the sub level property player.type.

['player.type']: e.target.value will only create a 'player.type' string property in root level but not override nor create sub-level property 'type' in player.

5
  • 1
    There's nothing built-in that will parse that. You need to split it into an array and then loop over the elements. Commented Feb 6, 2023 at 23:41
  • 1
    See stackoverflow.com/questions/8051975/… for how to do that. Commented Feb 6, 2023 at 23:43
  • ok, so i have to build a work-around. thank you! Commented Feb 6, 2023 at 23:44
  • It depends on whether this needs to be dynamic. See the answer below for how to do it with fixed properties. Commented Feb 6, 2023 at 23:44
  • i have dynamic input (key can be any object property on any level) Commented Feb 6, 2023 at 23:45

1 Answer 1

1

I think what you are asking for is:

const [key1, key2] = "player.type".split('.')
const playerDetails = {foo: 'bar'}, e = {target: {value: 12}}
const res = {...playerDetails, [key1]: {...playerDetails[key1] ?? {}, [key2]: e.target.value} }
console.log(res)

This approach is not feasible for more than two levels, though it works in a recursive algorithm too:

const data = {foo: 'bar', player: {name: 'baz'}}
const prop = "player.value.default"
const setProp = (obj, [prop, ...path], value) => !prop ? value : {...obj, [prop]: setProp(obj[prop] ?? {}, path, value)}
console.log(setProp(data, prop.split('.'), 42))
But there are more efficient ways to do it.

Sign up to request clarification or add additional context in comments.

7 Comments

what is key2 doing? i am passing key='player.type' and want it to create player: {type: someValue }
@instantlink In your example it says player.type, which I understood as player being key1 and type being key2.
@instantlink I think it is clearer now. This stuck with me a bit lol. Good question!
i had same idea of splitting the key but was asking if there was any trick to do it easier since it seems to be a quite common task to do
@instantlink Oh, it reads like you asked "how to use key to set the sub level property", i.e. how to use destructuring on a deeper level than just the first.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.