0

I have the following code in react. Trying to iterate over specific keys using array of keys in object which has keys with null values produces error data[title] is null like following :

let data = this.state.data 
    ["description",  "title"].forEach((key) =>
     {
      if(data[key] == "" || data[key] == null)
      {
        noErrors = false 
        errorsUpdate.push(`${key} field cannot be blank`)
      }
    }) 

However, using any of the following will not produce errors:

let data = this.state.data 
    let a = ["description",  "title"]
    for(let i = 0; i < a.length; i++)
     {
      if(data[a[i]] == "" || data[a[i]] == null)
      {
        noErrors = false 
        errorsUpdate.push(`${a[i]} field cannot be blank`)
      }
    }



let data = this.state.data 
let a = ["description",  "title"]
    for(let i of a)
     {
      if(data[i] == "" || data[i] == null)
      {
        noErrors = false 
        errorsUpdate.push(`${[i]} field cannot be blank`)
      }
    }

I don't have deep knowledge in JS. My question why browser produce an error when using forEach ?

youssef
  • 605
  • 3
  • 14
  • how does `data ` looks like? – brk May 15 '20 at 13:00
  • 2
    Add a semicolon after `let data = this.state.data`. IF you don't add that, your code becomes `let data = this.state.data["description", "title"].forEach` which in turn becomes `this.state.data["title"].forEach` because of comma operator – adiga May 15 '20 at 13:01
  • @adiga to my understanding semicolon is not important for statement. is there an exception in this case. thanks – youssef May 15 '20 at 13:03
  • 1
    Yeah semicolon is the problem. Because it will create ambiguity in the language parser and language parser will think `data[..` together. – Md Johirul Islam May 15 '20 at 13:07
  • @adiga yes I think it's working now – youssef May 15 '20 at 13:08

0 Answers0