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

144
Views
how to merge nested dynamic Object

I have a onChange method like this:

handleChange(e, fieldName, fieldType, index, parentEle) {}

inside this I am trying to store the value into a global object called as nestedObj my params are dynamic

expected object structure:

[parentEle]: {[index]: {[fieldName]: e.target.value}}

so after each onChange my object will be something like this:

fruit: {0: {fruitName: 'apple'}}
fruit: {0: {fruitId: 123}}
fruit: {1: {fruitName: 'orange'}}
fruit: {1: {fruitId: 456}}
car: {0: {carName: 'bmw'}}
car: {0: {carId: 789}}
car: {1: {carName: 'audi'}}
car: {1: {carId: 101}}

as fields are dynamic this is what I am doing:

const eachValue = { [index]: { [fieldName]: e.target.value } };

if (nestedObj?.[parentEle]?.[index]) {
  nestedObj[parentEle][index] = Object.assign(
    {},
    nestedObj[parentEle][index],
    eachValue[index]
  );
} 
else {
  nestedObj[parentEle] = eachValue;
}

so what I am receiving is this:

{
  fruit: {1: {fruitName: 'orange', fruitId: 456}} 
  car: {1: {carName: 'audi', fruitId: 101}} 
}

so I am making the mistake in else part as assigning the eachValue to object directly replacing the previous element

what I expect is:

{
  fruit: [{0: {fruitName: 'apple', fruitId: 123},
          {1: {fruitName: 'orange', fruitId: 456}] 
  car: [{0: {carName: 'bmw', fruitId: 789},
        {1: {carName: 'audi', fruitId: 101}] 
}

can you please guide me how to achieve this?

about 4 years ago · Juan Pablo Isaza
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!