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
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:
In the code above, you just add the object after you have exited the loop.
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: