11-18-2022, 12:36 PM
How to combine JS Objects with duplicate key/values
I want to try and combine the above two objects. I know they have the same key so I wanted to merge the values of each key if they are the same. Such as:
But this will merge both objects but it only retains the values from the right object. I was trying to do a for loop and add a check if the key is the same in both objects and then combine the values together but I keep getting lost and it is hard to visualize. If someone could help me understand how I can create a for loop to start the comparison that would help me in completing the rest.
Code:
cont oldCar = {
model: 'Honda',
notes: {
id: 1,
timestamp: 2000,
text: 'is old'
}
}
cont oldCar = {
model: 'Toyota',
notes: {
id: 1,
timestamp: 4000,
text: 'is new'
}
}
I want to try and combine the above two objects. I know they have the same key so I wanted to merge the values of each key if they are the same. Such as:
Code:
mode: 'Honda / Toyota'
But this will merge both objects but it only retains the values from the right object. I was trying to do a for loop and add a check if the key is the same in both objects and then combine the values together but I keep getting lost and it is hard to visualize. If someone could help me understand how I can create a for loop to start the comparison that would help me in completing the rest.