【问题标题】:Select certain items from array of objects to create new array in Typescript?从对象数组中选择某些项目以在 Typescript 中创建新数组?
【发布时间】:2021-02-12 11:52:02
【问题描述】:

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

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

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

【问题讨论】:

    标签: arrays angular typescript for-loop


    【解决方案1】:
    const infos = BOX.map(element => element.info);
    

    【讨论】:

    • 解释和文档链接将使这成为一个更好的答案。
    【解决方案2】:
    infos: string[] = BOX.forEach(element => element.info);
    

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

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

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

    【讨论】:

      【解决方案3】:

      您可以在 BOX-array 上使用 map 函数。它将返回一个新数组,其中包含您放入箭头函数的内容。如果你只想要元素的信息,你可以这样做

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

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

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

      Here are some more information about the topic

      【讨论】:

        猜你喜欢
        • 2020-07-09
        • 2020-02-23
        • 2021-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-26
        • 2021-06-15
        • 1970-01-01
        相关资源
        最近更新 更多