Ajith
Ajith

Reputation: 845

Update object property in javascript?

 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?

Upvotes: 0

Views: 62

Answers (3)

Harshith V
Harshith V

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

Maxx P
Maxx P

Reputation: 176

Try this

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

Upvotes: 1

Nikita Ivanov
Nikita Ivanov

Reputation: 856

Use this:

const updatedObject = {
  ...fields,
  address: {
    ...fields.address,
    [id]: value,
  },
};

Upvotes: 1

Related Questions