I'm wondering if it's possible to push an object to an array and if the id data-seats already exists replace/overwrite the value on next click.
Yes (see below), but if you're looking for a structure for storing things by a unique key, an array isn't really your best option. An object (created with Object.create(null)
so it doesn't inherit any properties) or Map
would be a better choice. Then you'd just do
// With an object
active_filters["data-seats"] = (active_filters["data-seats"] || 0) + 1;
or
// With a Map
active_filters.set("data-seats", (active_filters.get("data-seats") || 0) + 1);
Those work because if data-seats
isn't on the active_filters
object/Map, active_filters["data-seats"]
/active_filters.get("data-seats")
is undefined
, and undefined || 0
is 0
. (Then we add 1 to it, and set the new value.)
But you can do it with an array: Use find
to see if the object already exists and then update it if it does, or add it if it doesn't:
var obj = active_filters.find(function(entry) { return entry.id === "data-seats"; });
if (obj) {
++obj.value;
} else {
active_filters.push({id: "data-seats", value: 1});
}