skip to Main Content

I have an array with nested objects. What I want to achieve is to loop through the arrays objects and check if a key exists inside the object and if it does I want to replace the value of that object and break out of the loop. If the key doesn’t exist inside any of the objects I want to append a new object into the array and print the final array. What I tried below is not working. Where did I go wrong and how can I fix it? Thanks in advance.

x = [{
  "s": "23",
  "t": "41"
}, {
  "e": "29",
  "t": "87"
}]

for (var i = 0; i < x.length; i++) {
  if ("d" in x[i]) {
    x[i]["t"] = "21"
    console.log(x)
    break
  } else if (i === x.length - 1) {
    x.push({
      "v": "22",
      "t": "77"
    })
    console.log(x)

    //loop finised
  }
}

2

Answers


  1. The reason your code isn’t working because it enters an infinite loop. You’re mutating the array directly(by adding/pushing a new element) while looping through it. So the length keeps getting longer & longer resulting in infinite loop.

    Just change your code to the following:

    x = [{
      "s": "23",
      "t": "41"
    }, {
      "e": "29",
      "t": "87"
    }]
    
    let isKeyExists = false;
    
    for (var i = 0; i < x.length; i++) {
      if ("d" in x[i]) {
        x[i]["t"] = "21"
        console.log(x)
        isKeyExists = true;
        break
      }  
    }
    
    if (!isKeyExists) {
      x.push({
          "v": "22",
          "t": "77"
      })
    }
    
    console.log(x)
    

    In the code above, you just add the object after you have exited the loop.

    Login or Signup to reply.
  2. Your code is not working because you are trying to access the d key in the x array, but the d key does not exist in any of the objects in the x array. You can fix this by checking if the d key exists in the current object before you try to access it. You can do this by using the hasOwnProperty() method.

    Here is the corrected code:

    x = [{
      "s": "23",
      "t": "41"
    }, {
      "e": "29",
      "t": "87"
    }]
    
    for (var i = 0; i < x.length; i++) {
      if (x[i].hasOwnProperty("d")) {
        x[i]["t"] = "21"
        console.log(x)
        break
      } else if (i === x.length - 1) {
        x.push({
          "v": "22",
          "t": "77"
        })
        console.log(x)
    
        //loop finised
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search