I need to iterate over the array of objects in angular 2 and limit the string length display for a particular key in the object.
JavaScript
x
15
15
1
this.productService.loadAllProducts(product).subscribe(data => {
2
if (this.authService.checkActiveSession(data)) {
3
if (data.success) {
4
//console.log(this.product_desc.substring(0,2))
5
for(let i=0;i<data.products.length ;i++){ //How to properly iterate here!!
6
console.log(data.products[0].product_desc)
7
}
8
this.source.load(data.products);
9
} else {
10
console.log('Not binded');
11
}
12
}
13
});
14
}
15
I need to limit the prod_desc length to (say) 10 characters while displaying for which I have used:
Eg:
JavaScript
1
2
1
this.product_desc.substring(0,10)
2
Advertisement
Answer
You can use the built-in forEach
function for arrays.
Like this:
JavaScript
1
5
1
//this sets all product descriptions to a max length of 10 characters
2
data.products.forEach( (element) => {
3
element.product_desc = element.product_desc.substring(0,10);
4
});
5
Your version wasn’t wrong though. It should look more like this:
JavaScript
1
4
1
for(let i=0; i<data.products.length; i++){
2
console.log(data.products[i].product_desc); //use i instead of 0
3
}
4