I'm working with two array of JSON objects in Angular, both the dictionaries have "song_id" as similar key-value. I want to merge the "rating" key-value with the first array where the song_id matches.
Original Array 1:
this.Array1 = [
{"song_id": 01, "artist_name": "Arijit, Shreya", "song_name": "Song1"},
{"song_id": 02,"artist_name": "Jason, Ankit", "song_name": "Song2"},
{"song_id": 03,"artist_name": "Asha, Lata, Bapi", "song_name": "Song3"},
]
Original Array 2:
this.Array2 = [
{"song_id": 01, "user_id": 5, "rating": 4},
{"song_id": 02, "user_id": 5, "rating": 5},
{"song_id": 03, "user_id": 5, "rating": 3},
]
Expected Result:
this.Array1 = [
{"song_id": 01, "artist_name": "Arijit, Shreya", "song_name": "Song1", "rating": 4},
{"song_id": 02,"artist_name": "Jason, Ankit", "song_name": "Song2", "rating": 5},
{"song_id": 03,"artist_name": "Asha, Lata, Bapi", "song_name": "Song3", "rating": 3},
]
CodePudding user response:
You can idea from here:
let arr1 = [
{ song_id: 1, artist_name: 'Arijit, Shreya', song_name: 'Song1' },
{ song_id: 2, artist_name: 'Jason, Ankit', song_name: 'Song2' },
{ song_id: 3, artist_name: 'Asha, Lata, Bapi', song_name: 'Song3' },
];
let arr2 = [
{ song_id: 1, user_id: 5, rating: 4 },
{ song_id: 2, user_id: 5, rating: 5 },
{ song_id: 3, user_id: 5, rating: 3 },
];
arr1.map((item) => {
let songID = item.song_id;
arr2.map((item2) => {
let songID2 = item2.song_id;
if (songID === songID2) {
item['rating'] = item2.rating;
console.log(item);
}
});
});