-1

I have a state that looks like this:

attributes: [
{name: "capacity", items: [{ value: '256GB'},{value: '512GB'}]},
{name: 'With USB 3 ports', items: [{value: 'Yes'}, { value: 'No'}]}
]

I want to create a function which takes 2 paramaters, for example "capacity" and "256GB", I want to iterate over attributes state and find the object where the value property is 256GB and add another property in that object.

so I want the state to look like this:

attributes: [
{name: "capacity", items: [{ value: '256GB', selected: true},{value: '512GB', selected: false}]},
{name: 'With USB 3 ports', items: [{value: 'Yes'}, { value: 'No'}]}
]
bingbong
  • 1
  • 2
  • `for (attribute in attributes) { if attribute.items[0].value == '256GB' { attribute.items.push(something) } }` – Sasha Kondrashov Oct 20 '22 at 21:37
  • @SashaKondrashov [don't use `for...in` on an array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#array_iteration_and_for...in) and if this is stored in state don't mutate by pushing. – pilchard Oct 20 '22 at 21:45
  • see: [Updating deeply nested state with useState not working properly](https://stackoverflow.com/questions/69270887/updating-deeply-nested-state-with-usestate-not-working-properly) and [React State update a nested array with objects based on the id when iterated](https://stackoverflow.com/questions/71005652/react-state-update-a-nested-array-with-objects-based-on-the-id-when-iterated) for some discussion – pilchard Oct 20 '22 at 22:32
  • @pilchard whoops, I could have sworn I wrote "for...of", my bad :x – Sasha Kondrashov Oct 21 '22 at 13:13

1 Answers1

0

There are multiple ways to do this, the easiest way to do this is to use in-build javascript functions like map, and reduce as shown in the example below

Added an example at codesandbox on how this could be achieved. The part you need to be careful is when working with objects/arrays that hold state in react, is that you do not intend to mutate them. It's out of scope for this question to explain but to get a clear understanding of it research how javascript passes parameters.

Besnik Korça
  • 939
  • 3
  • 9