IT TIP

Angular 2 및 TypeScript로 두 개의 객체 배열을 병합 하시겠습니까?

itqueen 2020. 11. 2. 20:11
반응형

Angular 2 및 TypeScript로 두 개의 객체 배열을 병합 하시겠습니까?


이 주제에 대한 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.results어떻게 연결할 수 this.results있습니까?

this._slugthis._next클래스에 설정됩니다.

감사.


차라리 다음을 사용해야한다고 생각합니다.

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

로부터 concat 문서 :

concat () 메서드는 인수로 제공된 배열 및 / 또는 값과 결합 된 호출 된 배열로 구성된 새 배열을 반환합니다.


확산 운영자는 좀 냉각된다.

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

확산 연산자를 사용하면 확장 된 버전의 배열을 다른 배열에 쉽게 배치 할 수 있습니다.

여기에서 스프레드 연산자에 대해 읽을 수 있습니다.


각도 6 확산 연산자연결 이 작동하지 않습니다. 쉽게 해결할 수 있습니다.

result.push(...data);

ES6에서 권장하는 양식을 사용할 수도 있습니다.

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

이것은 배열을 먼저 초기화하면 작동합니다 ( public results = [];); 그렇지 않으면 교체 ...this.results,에 의해 ...this.results ? this.results : [],.

도움이 되었기를 바랍니다

참고 URL : https://stackoverflow.com/questions/38092458/merge-two-object-arrays-with-angular-2-and-typescript

반응형