1

My goal is to map over an array and replace objects that match a condition. Much like this working example:

const rows = [{
  "name": "Dad",
  "car": "Sedan"
}, {
  "name": "Mom",
  "car": "Sedan"
}]
const newCar = {
  "name": "Dad",
  "car": "Minivan"
}

const newArray = rows.map((r) => (r.name === newCar.name ? newCar : r))
console.log(newArray)

In my use case, component state contains the array, which is populated from an API.

  const [rows, setRows] = useState([])

Later, a change is required to one object in the array. The data variable contains the modified object to be merged into the array. I map over the array looking for matches on the _id field. When the _id matches, I return the object from data (the value to be merged into the array). When there is not a match, I return the object as it originally existed in state.

        setRows((rows) => [
          ...rows,
          rows.map((r) => (r._id === data._id ? data : r)),
        ])

The desired outcome is an array of the same size as the original. This new array should contain one modified object in addition to all original array values.

The actual results from the code above are that the modified data object is added rather than updated.

How can I change my code to replace the modified array element instead?

1 Answer 1

3

The useState() functional updates form calls a function and passes it the previous state. The Array.map() function returns a new array with the updated values. This means that you only need to map the previous state to get a new state:

setRows(rows => rows.map((r) => (r._id === data._id ? data : r)))
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.