如何在类型脚本中从数组中获取值?

xdnvmnnf  于 2022-09-18  发布在  Java
关注(0)|答案(4)|浏览(182)

我有一个看起来像这样的数组

const array: any[] = []
   array.push({ 'Comments': this.comment, 'Name': this.name, 'Description' : this.description })

我将该数组传递回父组件。我如何才能抓住评论中的价值?

zf9nrax1

zf9nrax11#

您可以使用forEach循环:

const commentArray = [];
array.forEach(function(object) {
    var comment = object.Comments;
    commentArray.push(comment);
});
//You can store all comments in another array and use it...
console.log("This is comment array...", commentArray);

或者使用MAP,但它将在新的浏览器中运行,可能是ES6之后的浏览器:

const commentArray = array.map(function(object) {
    return object.Comments;
});
console.log("This is comment array... ", commentArray);
edqdpe6u

edqdpe6u2#

只要TGW的答案是“正确的”并且有效,我认为您应该知道并使用for...of(和for...in)构造,它优于Arra.Each(速度更快,您可以使用Continue和Break关键字,更好的可读性),而且更多情况下,您希望迭代数组并使用它来做事情,而不是只获得一个属性(在本例中,Array.map非常适合:)

xoefb8l8

xoefb8l83#

您可以尝试这样做:

我们也可以在这里使用过滤器

let commentArray:any[];
array.filter(function(object) {
    var comment = object.Comments;
    commentArray.push(comment);
});
//Store here and use this.
console.log("This is comment array...", commentArray);
j91ykkif

j91ykkif4#

您可以使用下划线JS来获得更短、更好的性能,如下所示:

let ids: Array<number> = _.map(this.mylist, (listObj) => {
        return listObj.Id;
    });

相关问题