skip to Main Content

I have a JSON, and I want to loop through it but when i loop through it, due to the strings present with it, the loop is failing. How do i just loop through the objects in the JSON ?

I just want to iterate through the objects within that JSON.

  • I tried if(json.length!=3) but it fails when it hits the object because i think it cannot find a length for the object
  • I also tried json.hasOwnProperty("field_id") which is also failing when i hit the string "and"
  • I also tried if(json.length=undefined) which also fails because the length itself goes into undefined state

Here’s my JSON:

[
    {
        "field_id": 122,
        "operator_id": "1",
        "where_flag": true
    "and",
    {
        "field_id": 128,
        "operator_id": "0",
        "where_flag": true
    },
    "and",
    {
        "field_id": 148,
        "operator_id": "1",
        "where_flag": true
    }
]

2

Answers


  1. I’d recommend filtering the items first and then, looping over the objects:

    function isObject(value) {
      return typeof value === "object" && value !== null
    }
    
    array.filter(item => isObject(item)).forEach(...)
    

    or just squeezing them in one loop (which I don’t usually recommend):

    array.forEach(item => {
      if(!isObject(item)) return;
    
      ...
    })
    
    Login or Signup to reply.
  2. maybe this will work,

    let array = [
        {
            "field_id": 122,
            "operator_id": "1",
            "where_flag": true
        },
        "and",
        {
            "field_id": 128,
            "operator_id": "0",
            "where_flag": true
        },
        "and",
        {
            "field_id": 148,
            "operator_id": "1",
            "where_flag": true
        }
    ]
    
    array.forEach((elem)=>{
        if(typeof(elem)=="object"){
            console.log(elem)
        }
    })
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search