Reputation: 845
const [fields, setFields] = useState({
country: { country: "India" },
address: { street1: "street1", street2: "street2" },
});
This is my object. I want to update an inner property from this object
let id = 'street1'
let params = { ...fields, [id]: value }; //This will add a new prop
But i want to update the street1 inside the address object. How to do that?
Upvotes: 0
Views: 62
Reputation: 48
let userAddress = {
country: { country: "India" },
address: { street1: "street1", street2: "street2" },
};
I believe the situation is to update the value of object that is nested , in this case street1.
Best way with ES6 would be to destructure and update the value.
userAddress = {
...userAddress,
address: { ...state.address, street1: newValue },
};
Upvotes: 1
Reputation: 856
Use this:
const updatedObject = {
...fields,
address: {
...fields.address,
[id]: value,
},
};
Upvotes: 1