merge two object arrays with Angular 2 and TypeScript?

Rivadiz picture Rivadiz · Jun 29, 2016 · Viewed 178.3k times · Source

I have gone across the JavaScript questions on this topic, this question is specifically about Angular2 with TypeScript.

What I am trying to do is to concatenate the json objects to an array.

My code looks something like this,

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);
            }
        );
}

How can I concatenate data.results to this.results with typescript and angular?

this._slug and this._next are set on class.

thanks.

Answer

Amsakanna picture Amsakanna · Oct 12, 2017

The spread operator is kinda cool.

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

The spread operator allows you to easily place an expanded version of an array into another array.

You can read about spread operator here.