Search code examples
javascriptternary

Using typeof in ternary


Im looping(hence the i) through a json object(jobj) and checking values, changing them if necessary.

(jobj["Level_Objects"][i]["x"] <0 || jobj["Level_Objects"][i]["x"]>0) ? true : jobj["Level_Objects"][i]["x"]=0;

That works as expected, allowing for neg and pos numbers and setting it to 0 if neither.

My problem is that I want to check using typeof as well, none of the syntax iv tried works.

(typeof jobj["Level_Objects"][i]["x"]==="number" || jobj["Level_Objects"][i]["x"] <0 || jobj["Level_Objects"][i]["x"]>0) ? true : jobj["Level_Objects"][i]["x"]=0;

Solution

  • Try the following, it will will assign zero if the value is not a number.

    const value = jobj['Level_Objects'][i]['x']
    
    if (typeof value !== 'number') {
      jobj['Level_Objects'][i]['x'] = 0
    }
    // or without the if
    jobj['Level_Objects'][i]['x'] = typeof value === 'number' ? value : 0