从对象数组中选择某些项目以在Typescript中创建新数组?

时间:2020-10-30 00:44:47

标签: arrays angular typescript for-loop

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

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[]'

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

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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

Array.prototype.forEach从定义中返回undefined。 对于每个数组元素,它只执行一次提供的功能。

因此,在您的情况下,您需要使用Array.prototype.map函数为每个元素映射info参数。

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

答案 2 :(得分:1)

您可以在BOX阵列上使用map功能。它将返回一个新数组,其中包含您在arrow函数中输入的内容。如果只需要元素的信息,则可以这样做

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

上面有一个隐式return语句,是下面相同函数的简写。

infos: string[] = BOX.map(element => {
   return element.info;
});

Here are some more information about the topic