2

I have an array of objects. In that array, I want to update a single object, and in that object, I want to update only specific properties. I tried:

setRequiredFields(prevRequiredFields => ([
            ...prevRequiredFields, prevRequiredFields.find(x => x.name = field) ?  {
                isValid: isValid,
                content: content,
                isUnchanged: false
            }
]));

But it didn't work. Required fileds is an array with the following structure:

[{
    name: "Name",
    isValid: false,
    content: "",
    isUnchanged: true,
    tip: "Name cannot be empty",
    isValidCondition: notEmptyRegex,
    reportState: validateField
}]

What I'm trying to do here is to update only a isValid, content and isUnchanged of one specific object inside that array. How can I accomplish that?

2
  • 2
    Why not use .map instead then? Just do setRequiredFields(prevRequiredFields.map(item => item.name === field ? {...item, isValid, content, isUnchanged: false} : item) Commented Aug 1, 2021 at 18:43
  • share reproducable example Commented Aug 1, 2021 at 18:53

1 Answer 1

4

If you have an array of objects, and you want to update few properties of one of the objects inside the array. Then you could do something like this.

const index = state.findIndex(x => x.name === field);
if(index > -1) {
  const newState = [...state];
  newState[index] = { 
    ...newState[index],
    isValid: isValid,
    content: content,
    isUnchanged: false
  }
  setRequiredFields(newState);
}
  • Find the index of the object that you want to update.
  • Add properties inside that object.
  • Update the react state.
Sign up to request clarification or add additional context in comments.

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.