Skip to content

Instantly share code, notes, and snippets.

@joecarney
Created September 14, 2016 21:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joecarney/1d7df3a95488f07b364ea5558d7bbfbf to your computer and use it in GitHub Desktop.
Save joecarney/1d7df3a95488f07b364ea5558d7bbfbf to your computer and use it in GitHub Desktop.
How to set a nested object value when the key is a variable name
const action = {
id: "last_name",
value: "Carney"
};
const state = {
inputs: {
first_name: {
value: "Joe"
},
last_name: {
value: ""
}
}
};
const newState = Object.assign({}, state, {
inputs: Object.assign({}, state.inputs, {
[action.id]: Object.assign({}, state.inputs[action.id], {
value: action.value
})
})
});
/*
console.log(newState)
{
inputs: {
first_name: {
value: "Joe"
},
last_name: {
value: "Carney"
}
}
}
*/
@nicnocquee
Copy link

Don't know how to do it in one line, but can only think of this.

var newInputs = {...state.inputs}
newInputs[action.id] = action.value
const newState = {
  ...state,
  inputs: newInputs
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment