Skip to content
Advertisement

How sum specific array values with input onChange

I’m have a list of objects

JavaScript

I need to sum two values in array with onChange input

On every change values is summed

JavaScript

I’m create input form and it’s works but change all my mapped values at once

JavaScript

How can i change only one item in array at once on every onChange event?

Advertisement

Answer

You can make inputValue store an object. The object can hold each objects id as its key and its associated sum. When mapping over your list, use the id of the current object your iterated on to obtain the value from inputValue. Within your onChange, you can pass the current objects id so that you can update it when you set your object state, eg:

JavaScript

Now when you acceess your value, access it via the id of the current object. Below I’m using ?? 0 to use the value of 0 if inputValue[el.id] is undefined due to el.id not being set:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement