Reputation: 71
Currently I am looping over JSON data using nested forEach. But I would like to know is there any other simple and feasible approach is available in typescript or RXJS because I'm iterating over an Observable as well in few scenarios. Here is the code snippet and stackblitz https://stackblitz.com/edit/angular-dz3wl2?file=src%2Fapp%2Fapp.component.ts
Iterating over the JSON should return me the object having the property "type" in htmltypes array and in inlineTags array. Can someone please guide me in retrieving the object which i wanted without using forEach method .
content.data.areas.forEach(sectionBlock => {
sectionBlock.sections.forEach(obj => {
obj.htmltypes.forEach(val => {
console.log(val);
if (val.inlineTags.length > 0) {
val.inlineTags.forEach(tag => {
console.log(tag);
})
}
})
})
})
Upvotes: 1
Views: 192
Reputation: 12021
there is no simpler way to do that, but you can make it less nested with some rxjs or array operators for example Array.prototype.flatMap
, but to use it you should include polyfill for it like core-js/es7/array/flat-map
. your code will look like
content.data.areas
.flatMap(sectionBlock => sectionBlock.sections)
.flatMap(obj => obj.htmltypes)
.flatMap(val => val.inlineTags)
.forEach(tag => console.log(tag));
with rxjs it can be done in some way like
from(content.data.areas).pipe(
concatMap(sectionBlock => sectionBlock.sections)
concatMap(obj => obj.htmltypes)
concatMap(val => val.inlineTags)
).subscribe(tag => console.log(tag));
Upvotes: 1