[arrays] merge two object arrays with Angular 2 and TypeScript?

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.

This question is related to arrays typescript angular

The answer is


try this

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

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.


With angular 6 spread operator and concat not work. You can resolve it easy:

result.push(...data);

Assume i have two arrays. The first one has student details and the student marks details. Both arrays have the common key, that is ‘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 },
];

I want to merge the two arrays based on the key ‘studentId’. I have created a function to merge the two arrays.

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

here is the code to get the final result

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}
]

You can also use the form recommended by ES6:

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

This works if you initialize your array first (public results = [];); otherwise replace ...this.results, by ...this.results ? this.results : [],.

Hope this helps


Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7