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

170
Views
React - update object within object within array

Having trouble updating a field whose value if within an object within an object within an array:

      [
        { animals: { an1: 'lynx', an2: 'tiger' }, location: 'asia' },
        { animals: { an1: 'pigeon', an2: 'eagle' }, location: 'europe' },
      ];
const handleChange = (e, input) => {
    let updatedList = data.map((item, i) => {
        if (i === index) {
          const allAnimals = { ...item.animals };
          allAnimals[input] = e.target.value;

          return { ...item, animals: allAnimals }; 
        }
        return item;
      });
    
    setData(updatedList);

  }

How would I update an1 or an2 in the animals object?

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

0

If you simply would like to replace all indexes the following should work:

const data = [
  { animals: { an1: 'lynx', an2: 'tiger' }, location: 'asia' },
  { animals: { an1: 'pigeon', an2: 'eagle' }, location: 'europe' },
];

const handleChange = (e, input) =>
   data.map(it => ({
    ...it,
    animals: {
      ...it.animals,
      [input]: e.target.value,
    }
  }))

console.log(handleChange({
  target: {
    value: 'test',
  }},
  'an2'
))

Notice, that this will replace/add the new value to each array.

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!