0

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.

Code:

var active_filters = [];
$("a").on('click', function() {
    active_filters.push({id: "data-seats", value: increment_value });
});
Michael
  • 403
  • 1
  • 9
  • 28

1 Answers1

2

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});
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thanks so much TJ, this is perfect! Quick question...If using the method where I'm first checking if the object exists using find...if the value ever == 0, how can I then remove this object data-seats from array? – Michael May 04 '18 at 15:07
  • @Michael: For that, you wouldn't use `find`, you'd use [`findIndex`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex) and then `splice` with the resulting index. – T.J. Crowder May 04 '18 at 15:19