0
 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 

Params result

But i want to update the street1 inside the address object. How to do that?

0

3 Answers 3

1

Use this:

const updatedObject = {
  ...fields,
  address: {
    ...fields.address,
    [id]: value,
  },
};
Sign up to request clarification or add additional context in comments.

Comments

1

Try this

{...fields,address:{...fields.address,"street1":"abc"}}

Comments

1
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 },
};

Comments

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.