HHow to merge different arrays with similar object property?
I have two different arrays as below.
1st Array : arr1
0: {ID: '1', Name: 'Suyog Patil', IsSelected: false, Location: 'Mumbai'}
1: {ID: '2', Name: 'John Doe', IsSelected: false, Location: 'London'}
2: {ID: '3', Name: 'Santosh Sarnobat', IsSelected: false, Location: 'Panvel'}
3: {ID: '4', Name: 'Sai Panhalkar', IsSelected: false, Location: 'Belapur'}
2nd Array : arr2
0: {ID: '1', IsSelected: true}
1: {ID: '3', IsSelected: true}
Now, I want the replace the properties of array1 with properties of array2 where ID property is same.
So, the final array would look like (I need to get below output)
0: {ID: '1', Name: 'Suyog Patil', IsSelected: true, Location: 'Mumbai'} //Replaced value
1: {ID: '2', Name: 'John Doe', IsSelected: false, Location: 'London'}
2: {ID: '3', Name: 'Santosh Sarnobat', IsSelected: true, Location: 'Panvel'} //Replaced value
3: {ID: '4', Name: 'Sai Panhalkar', IsSelected: false, Location: 'Belapur'}
Here, you can see, IsSelected property is replaced to true where ID equals 1 & 3.
This is what I have tried so far, but not able to achieve.
arr3 = [].concat(arr1, arr2);
But, it gives 6 results, it literally concats as the function says
Solution 1:
Here is a non-jQuery version using much simplified code
const arr1 = [
{"ID":"1","Name":"Suyog Patil","IsSelected":false,"Location":"Mumbai"},
{"ID":"2","Name":"John Doe","IsSelected":false,"Location":"London"},
{"ID":"3","Name":"Santosh Sarnobat","IsSelected":false,"Location":"Panvel"},
{"ID":"4","Name":"Sai Panhalkar","IsSelected":false,"Location":"Belapur"}
],
arr2 = [{"ID":"1","IsSelected":true}, {"ID":"3","IsSelected":true}],
arr3 = arr1.map(item => ({...item,IsSelected: arr2.find(({ID}) => ID === item.ID) || false}))
console.log("-----ARRAY 3-----");
console.log(arr3);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>