Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break loop over TypeScript object properties

I would like to iterate over object properties with TypeScript. But I would like to stop as soon as a specific object has been found.

Something like:

function hasElement() {
    let obj = {
        a: 'a',
        b: 'b',
        c: 'c'
    }
    let found = false;
    for (let i = 0; i < Object.keys(this.obj).length && !found; i++) {
        let prop = obj[i];
        found = prop === 'a';
    }
    return found;
}
console.log(hasElement());

But obj[i] doesn't work because the key is not a number. Of course I could use break or jump to labels but it is ugly in my opinion as I would rather like to specify the loop condition in the first place.

like image 439
Sandro Avatar asked Sep 13 '26 21:09

Sandro


2 Answers

That's not how you iterate an object with TypeScript. You're looking for for..of:

for (const key of Object.keys(obj)) {
  if (obj[key] === 'a') { return true; }
}
return false;

You can also use .find():

const matchingKey = Object.keys(obj).find(key => obj[key] === 'a');
return Boolean(matchingKey); // convert to boolean.
like image 107
Madara's Ghost Avatar answered Sep 17 '26 07:09

Madara's Ghost


You could use Array.filter or Array.find for that.

Array.filter will go trough the entire list but there's better support for it.

let found = Object.keys(obj).filter(key => obj[key] == 'a')[0]

Array.find should be exactly what you need but it lacks support on some browsers.

let found = Object.keys(obj).find(key => obj[key] == 'a');

IE lacks support for it. You can find the MDN documentation here.

like image 41
toskv Avatar answered Sep 17 '26 05:09

toskv