Home > Net >  How to pass an object and only change one value?
How to pass an object and only change one value?

Time:01-31

I have a data object below.

{
  name: "Catherine Myer",
  age: 23,
  birthday: "august"
}

If in need to pass the data as a prop to a component, BUT would also like to change just the age to: 24. How do i do so?

<NextPage data={author.age = 24}/>

I need the final object to be:

{
  name: "Catherine Myer",
  age: 24,
  birthday: "august"
}

CodePudding user response:

You can do it with spread syntax:

<NextPage data={{...author, age: 24}}/>

CodePudding user response:

Either pass individual prop values by spreading author (see Spread Attributes) and override age with a separate prop, eg

const NextPage = ({ name, age, birthday }) => {
  // ...
};

<NextPage {...author} age="24" />

or extend the existing object and provide a new age property

const NextPage = ({ data: { name, age, birthday } }) => {
  // ...
};

<NextPage data={{...author, age: 24}} />

CodePudding user response:

If you don't know which property will be overwritten, a simple for in loop can make the update. As a bonus, this scales up if you want to modify the value of more than one property at once.

Alternatively, if you really want to (or if you make the change Mike Kamermans recommended), you can use the JS spread syntax to achieve the same.

const author = {
  name: "Catherine Myer",
  age: 23,
  birthday: "august"
};

const data = { 
  age: 24
};

// OPTION 1: for in loop
let updatedAuthor = { ...author }; // optionally create a copy to avoid mutating the original object
for(let prop in data) {
  updatedAuthor[prop] = data[prop];
}

// OPTION 2: spread syntax
const propToUpdate = Object.keys(update)?.[0];
const updatedAuthor = {
  ...author,
  [propToUpdate]: update[propToUpdate]
}
  • Related