I have two arrays of objects
let current = [
{
categoryId: 18,
id: 'fire_18',
test: 'test'
}, {
oldItem: "items that dont exist in new array should be deleted"
}
]
let new_data = [
{
id: 'fire_18',
categoryId: 18,
test1: 'test1',
}, {
newItem: "new items should be added to final"
}
]
I need to merge those so the result is not missing data from current array. The desired result looks like this
[
{
id: 'fire_18',
categoryId: 18,
test1: 'test1',
test: 'test'
}, {
newItem: "new items should be added to final"
}
]
Here is my attempt
let current = [
{
categoryId: 18,
id: 'fire_18',
test: 'test'
}, {
oldItem: "items that dont exist in new array should be deleted"
}
]
let new_data = [
{
id: 'fire_18',
categoryId: 18,
test1: 'test1',
}, {
newItem: "new items should be added to final"
}
]
console.log(' === Current ==>', current);
console.log(' === New ==>', new_data);
new_data.map(newItem => {
let currentMatch;
try { // incase new item newItem.categoryId wont exist
currentMatch = current.find(c => c.categoryId == newItem.categoryId) || {};
} catch (error) { // in that case, no need to merge
currentMatch = {};
}
return Object.assign(currentMatch, newItem);
});
console.log(' === Merged ==>', new_data);
the main thing wrong still is test key from the current arr is missing after merge.
Can anyone modify the pen to not delete keys from the current arr?
nameandslugNamecome from in your expected results?newItemandoldItemactually in the data?