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?
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.