Javascript 迭代 Typescript 中的对象数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46213989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterate over array of objects in Typescript
提问by Sushivam
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.
我需要遍历 angular 2 中的对象数组,并限制对象中特定键的字符串长度显示。
this.productService.loadAllProducts(product).subscribe(data => {
if (this.authService.checkActiveSession(data)) {
if (data.success) {
//console.log(this.product_desc.substring(0,2))
for(let i=0;i<data.products.length ;i++){ //How to properly iterate here!!
console.log(data.products[0].product_desc)
}
this.source.load(data.products);
} else {
console.log('Not binded');
}
}
}); }
}); }
I need to limit the prod_desc length to (say) 10 characters while displaing for which i have used:
我需要将 prod_desc 长度限制为(例如)10 个字符,同时显示我使用的:
Eg:
例如:
this.product_desc.substring(0,10)
回答by Wernerson
You can use the built-in forEachfunction for arrays.
您可以使用forEach数组的内置函数。
Like this:
像这样:
//this sets all product descriptions to a max length of 10 characters
data.products.forEach( (element) => {
element.product_desc = element.product_desc.substring(0,10);
});
Your version wasn't wrong though. It should look more like this:
不过你的版本没有错。它应该看起来更像这样:
for(let i=0; i<data.products.length; i++){
console.log(data.products[i].product_desc); //use i instead of 0
}
回答by Hubert Schumacher
In Typescript and ES6 you can also use for..of:
在 Typescript 和 ES6 中,您还可以使用 for..of:
for (var product of products) {
console.log(product.product_desc)
}
which will be transcoded to javascript:
这将被转码为 javascript:
for (var _i = 0, products_1 = products; _i < products_1.length; _i++) {
var product = products_1[_i];
console.log(product.product_desc);
}

