How can I cycle through states in an array in React?

Viewed 16

I need to implement a button that cycles through these states in this array so that when the button is clicked State_1 in each object becomes State_2, then State_2 becomes State_3 and then goes back to State_1. The tricky part for me so far has been figuring out how to cycle only through the states in each object. Any suggestions would be greatly appreciated!

  "people": [
    {
      "name": "Alice",
      "State_1": "Apple",
      "State_2": "Cherry",
      "State_3": "Dates"
    },
    {
      "name": "Bob",
      "State_1": "Banana",
      "State_2": "Plumb",
      "State_3": "Clementine"
    },
    {
      "name": "Eve",
      "State_1": "Grapes",
      "State_2": "Apricots",
      "State_3": "Grapefruit"
    }
  ]
}
1 Answers

So you want something like this? Let me know if I understood your question correctly.

const people = [
    {
      "name": "Alice",
      "State_1": "Apple",
      "State_2": "Cherry",
      "State_3": "Dates"
    },
    {
      "name": "Bob",
      "State_1": "Banana",
      "State_2": "Plumb",
      "State_3": "Clementine"
    },
    {
      "name": "Eve",
      "State_1": "Grapes",
      "State_2": "Apricots",
      "State_3": "Grapefruit"
    }
]

var saveState1
people.forEach(p => {
  saveState1 = p.State_1
  p.State_1 = p.State_2
  p.State_2 = p.State_3
  p.State_3 = saveState1
});

console.log(people)

Related