使用Angular 2和TypeScript合并两个对象数组?

时间:2016-06-29 06:59:05

标签: arrays typescript angular

我已经浏览了关于此主题的JavaScript问题,这个问题特别是关于带有TypeScript的Angular2。

我要做的是将json对象连接到数组。

我的代码看起来像这样,

public results: [];


public getResults(){
    this._service.get_search_results(this._slug, this._next).subscribe(
            data => {
                this.results.concat(data.results);
                this._next = data.next;
            },
            err => {
                console.log(err);
            }
        );
}

如何使用typescript和angular将data.resultsthis.results连接起来?

this._slugthis._next在课堂上设置。

感谢。

6 个答案:

答案 0 :(得分:94)

点差运算符有点酷。

this.results = [ ...this.results, ...data.results];
  

扩展运算符允许您轻松地将扩展版本的数组放入另一个数组中。

You can read about spread operator here.

答案 1 :(得分:86)

我认为您应该使用以下内容:

data => {
  this.results = this.results.concat(data.results);
  this._next = data.next;
},

来自concat doc

  

concat()方法返回一个新数组,该数组由调用它的数组组成,并与作为参数提供的数组和/或值连接。

答案 2 :(得分:15)

使用角度6的传播算子 concat 无效。您可以轻松解决它:

result.push(...data);

答案 3 :(得分:4)

您也可以使用ES6推荐的表格:

data => {
  this.results = [
    ...this.results,
    data.results,
  ];
  this._next = data.next;
},

如果您首先初始化数组(public results = [];),这是有效的。否则请...this.results,替换...this.results ? this.results : [],

希望这有帮助

答案 4 :(得分:2)

尝试

 data => {
                this.results = [...this.results, ...data.results];
                this._next = data.next;
            }

答案 5 :(得分:0)

假设我有两个数组。第一个有学生详细信息, 学生标记细节。两个数组都有公共密钥,即 ‘studentId’

let studentDetails = [
  { studentId: 1, studentName: 'Sathish', gender: 'Male', age: 15 },
  { studentId: 2, studentName: 'kumar', gender: 'Male', age: 16 },
  { studentId: 3, studentName: 'Roja', gender: 'Female', age: 15 },
  {studentId: 4, studentName: 'Nayanthara', gender: 'Female', age: 16},
];

let studentMark = [
  { studentId: 1, mark1: 80, mark2: 90, mark3: 100 },
  { studentId: 2, mark1: 80, mark2: 90, mark3: 100 },
  { studentId: 3, mark1: 80, mark2: 90, mark3: 100 },
  { studentId: 4, mark1: 80, mark2: 90, mark3: 100 },
];

我想基于键“ studentId”合并两个数组。我有 创建了一个合并两个数组的函数。

const mergeById = (array1, array2) =>
    array1.map(itm => ({
      ...array2.find((item) => (item.studentId === itm.studentId) && item),
      ...itm
    }));

这是获得最终结果的代码

let result = mergeById(studentDetails, studentMark);

[
{"studentId":1,"mark1":80,"mark2":90,"mark3":100,"studentName":"Sathish","gender":"Male","age":15},{"studentId":2,"mark1":80,"mark2":90,"mark3":100,"studentName":"kumar","gender":"Male","age":16},{"studentId":3,"mark1":80,"mark2":90,"mark3":100,"studentName":"Roja","gender":"Female","age":15},{"studentId":4,"mark1":80,"mark2":90,"mark3":100,"studentName":"Nayanthara","gender":"Female","age":16}
]