首页 > 解决方案 > 如何将一个数组连接到另一个数组,该数组的类型是从另一个继承的

问题描述

我有一个扩展 shoppingItem.model 的成分模型,以实现与购物模型中相同的参数,以便稍后将成分数组连接到我的购物清单数组。我已经尝试了以下代码,但它没有被添加到我的购物清单数组中。

addIngredientsToShoppingList(ingredients:Ingredient[]){
        this.shoppingList.concat(ingredients);
        console.log(this.shoppingList.slice());
        this.shoppingListChanged.emit(this.shoppingList.slice());
    }

这里成分类型是从 shoppingItem.model 继承的,我是否必须先将成分类型转换为 shoppingItem 类型才能将其连接到我的 shoppingList 中,或者我该怎么办?

标签: angulartypescript

解决方案


合并两个数组:

它采用所有数组进行连接,并映射 a(整个数组)的分配单个元素的结果,稍后将 c 作为项目与 b 和项目 b[i]。

var array1 = [{ id: "abdc4051", date: "2017-01-24" }, { id: "abdc4052", date: "2017-01-22" }],
        array2 = [{ id: "abdc4051", name: "ab" }, { id: "abdc4052", name: "abc" }],
        result = [array1, array2].reduce((a, b) => a.map((c, i) => Object.assign({}, c, b[i])));

    console.log(result);

推荐阅读