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 :
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.