-4

I have the following code

let branch_timings=locations.branch_timings;
for(let key of Object.keys(branch_timings)){
  branch_timings[key].timingsEnabled=false;
}

console.log(locations);

I tried converting this to while loop like this:

let keys=locations.keys()
let i=0;
while(i<keys.length)
{
    let key=keys[i];
    branch_timings[key].timingsEnabled=false;
    i++;
}

console.log(locations);

when I run my while loop code this is the error I get

TypeError: locations.keys is not a function

This is part of a bigger code from a question i posted earlier. Every solution I have found is in either for loop or forEach I am trying to learn how to convert these loops to while. I am fairly new to javascript, your opinions will be appreciated.

3 Answers3

1

You need Object.keys to enumerate keys.

let keys=Object.keys(locations);
let i=0;
while(i<keys.length)
{
    let key=keys[i];
    branch_timings[key].timingsEnabled=false;
    i++;
}

console.log(locations);
TheMisir
  • 4,083
  • 1
  • 27
  • 37
  • To expand on why this is correct vs. the OP's example, the answer lies in the fact that [`Object.keys()` is not a prototype method](https://stackoverflow.com/questions/57017736/why-is-object-keys-method-not-added-to-object-prototype). – esqew Aug 20 '20 at 14:29
0

Correct translation should be that.

let keys= Object.keys(locations.branch_timings);
let i=0;
while(i < keys.length)
{
    let key=keys[i];
    locations.branch_timings[key].timingsEnabled=false;
    i++;
}
Eclipse
  • 3
  • 2
0

To use locations.keys() Make Sure your variable location is of type Array. The TypeError you're getting suggests the variable location is not an Array.

If it's an object, you should use Object.keys(locations).

Nick Thakkar
  • 862
  • 1
  • 9
  • 13