Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

189
Views
How to update and target the right index in an array which is nested in an object?

I have the following react state, I want to update the second value not the whole object and I don't want to use an object as a value either, for now I can only change the whole object but not the specific wanted value how to target and update the wanted index.

// State 
const [state, setState] = useState({
    element: [false, 'starter text']
 });
  
// Update State logic
 setState({ ...state, element: [(element[1] = 'updated text')] });

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

When updating state in React you shallow copy the state, and nested state, that you are updating. For arrays this means you shallow copy the array.

// State 
const [state, setState] = useState({
  element: [false, 'starter text']
});
  
// Update State logic
setState(state => ({
  // shallow copy any previous root-level state
  ...state,

  // shallow copy the previous state's element array
  // when the mapped index matches the index you want to update
  // return the updated value, otherwise return existing value
  element: state.element.map((el, i) => i === 1 ? 'updated text' : el)
}));

If the array was an array of objects then you need to shallow copy them as well, then update the nested property.

Example:

element: state.element.map(
  (el, i) => i === 1
    ? {
      ...el,
      nestedProperty: 'updated text'
    }
    : el
)

I know this Immutable Update Patterns doc is from Redux, but is solves many common React state update issues.

about 4 years ago · Juan Pablo Isaza Report

0

You can create a new state state as codeSandbox

   setState(oldState => {
     const newState = { ...oldState, element: [ ...oldState.element ]};
     newState.element[1] = "updated text";
     return newState;
   })
about 4 years ago · Juan Pablo Isaza Report

0

You can use Object.assign. Since an array is an Object with indices as its properties, you can do this:

const arr = [1, 2, 3, 4, 5];
const updatedArr = Object.assign([], arr, { 1: 10 }); // Update value at index 1.

console.log(arr);
console.log(updatedArr);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!