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?