0

I am a beginner in javascript and I have a question. This array represents the "dataState" in the forloop. But somehow I cannot access the id with "item.id" and so the first condition never triggers and in the else case, the item.id pops out as undefined. Any idea?

[
    {
        "name": "a",
        "secName": "b",
        "tel": "+ 123 737 159 028",
        "note": "qw",
        "id": "B_A"
    }
]
for(const item in dataState){
        console.log(item)
        if(item.id===state.secName.toUpperCase() + "_" + state.name.toUpperCase()){
          setId("11")
          console.log("green")
        }else{
          setId(state.id)
          console.log(item.id)
          console.log(dataState)
          console.log("red")
        }
      }
jenlee123
  • 133
  • 1
  • 10
  • Is this React? Is `setId` updating a React state? If so you can't immediately log that state because state updates are asynchronous. – Andy Mar 11 '22 at 17:14
  • Yes, its React...what would be the way to go then? – jenlee123 Mar 11 '22 at 17:15
  • what do you get when you console.log(item)? – Sean Mar 11 '22 at 17:16
  • [Add in a `useEffect`](https://reactjs.org/docs/hooks-effect.html): `useEffect(() => console.log(id), [id]);` so that it logs the new state depending on changes to that state – Andy Mar 11 '22 at 17:17
  • 1
    A `for ... in` loop iterates over the **keys** of an object. Thus `item` in your case will be 0. What you want is `for ... of` to iterate over the values. – Pointy Mar 11 '22 at 17:18

0 Answers0