I am trying to write a basic function that will decide whether the object already exists in array of objects based on unique id that is inside this object as a property. Upon searching I came up with this code, and it seems to be doing the job fine, but I can imagine there is a better and faster way to determine whether to push or update the object. If you could share your best answer for this please...
var myArray = [
{
id: 1,
car: "Ford"
},
{
id: 2,
car: "Honda"
}
];
var objToOverwrite = {
id: 1,
car: "Bentley" // to overwrite car: "Ford"
};
var objToPush = {
id: 3,
car: "Toyota"
};
function pushToArray ( arr, obj ) {
var existingIds = arr.map((obj) => obj.id);
if (! existingIds.includes(obj.id)) {
arr.push(obj);
} else {
arr.forEach((element, index) => {
if (element.id === obj.id) {
arr[index] = obj;
};
});
};
};
pushToArray ( myArray, objToPush );
console.log(myArray);