Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

replace the value of a nested object if key exists

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
  }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading