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


91

我已经讨论了有关此主题的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);
            }
        );
}

我怎么可以连接data.resultsthis.results与打字稿和角?

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

谢谢。

Answers:


121

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

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

concat 文档

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


1
不幸的是,这不适用于Uint8arrays :(
Frederick Nord

如果this.results为null或未定义,可能会失败
Michael Freidgeim


35

与角6传播算子concat不起作用。您可以轻松解决:

result.push(...data);

来到这里寻找解决方案,同时保持方法之间的对象引用。这工作得很好。谢谢
jgritten

这不会合并数组,而是将数据从第二个添加到第一个。尽管可以完成这项工作,但由于它会修改原始数组,因此需要注意。
达沃

5

您还可以使用ES6建议的格式:

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

如果您先初始化数组(public results = [];),则此方法有效。否则取代...this.results,...this.results ? this.results : [],

希望这可以帮助



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}
]
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.