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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With