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"}]
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.
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.
TypeScript - Array concat() concat() method returns a new array comprised of this array joined with two or more arrays.
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"}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With