Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging 2 arrays based on one common key angular 2

I have 2 arrays in Angular 2 and I want to merge them based on one key value.

Array 1 :

[{"columnId":1,"type":"value 1"},{"columnId":2,"type":"value 2"}]

Array 2 :

[{"columnId":1,"field":"field 1"},{"columnId":2,"field":"field 2"}]

And so I want final result as

[{"columnId":1,"field":"field 1","type":"value 1"},{"columnId":2,"field":"field 2","type":"value 2"}]
like image 447
Jeeten Parmar Avatar asked Jan 18 '17 10:01

Jeeten Parmar


People also ask

How do I merge two arrays with the same key?

The array_merge_recursive() function merges one or more arrays into one array. The difference between this function and the array_merge() function is when two or more array elements have the same key. Instead of override the keys, the array_merge_recursive() function makes the value as an array.

How do I combine two arrays from another array?

To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.

How do I combine two arrays in TypeScript?

TypeScript - Array concat() concat() method returns a new array comprised of this array joined with two or more arrays.


1 Answers

This should do what you want:

const arr1 = [{"columnId":1,"type":"value 1"},{"columnId":2,"type":"value 2"}];
const arr2 = [{"columnId":1,"field":"field 1"},{"columnId":2,"field":"field 2"}];

const result = arr1.map(val => {
    return Object.assign({}, val, arr2.filter(v => v.columnId === val.columnId)[0]);
});

console.log(result);
// [{"columnId":1,"field":"field 1","type":"value 1"},{"columnId":2,"field":"field 2","type":"value 2"}]
like image 174
Santanu Biswas Avatar answered Nov 15 '22 12:11

Santanu Biswas