首页 > 解决方案 > 从对象数组中选择某些项目以在 Typescript 中创建新数组?

问题描述

我想从一个单独的数组对象中创建一个字符串数组。

export interface box{
    image: string,
    link: string,
    button_name: string,
    info: string, 
    description: string
}

export const BOX: box[] = [
    {image: 'image here', link: 'google.com',
    button_name: 'name', info: 'some information', description: "a description"
    },

    {image: 'image here again', link: 'another google.com',
    button_name: 'another name', info: 'some more information', description: "another description"
    },
]

本质上,我想从现有信息中创建一个新数组,但它只是一个信息数组。我不确定如何在打字稿中实现这一点。我试过像这样使用 ForEach 函数:

infos: string[] = BOX.forEach(element => element.info);

但这会给我一个错误,说

Type 'void' is not assignable to type 'string[]'

如何创建仅包含现有数组的信息字段的字符串数组?

标签: arraysangulartypescriptfor-loop

解决方案


const infos = BOX.map(element => element.info);

推荐阅读