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 });
});
5
  • Yes, that's possible! What have you tried so far? Commented May 4, 2018 at 14:48
  • So far, I have the above with getting the object pushed to the array :) Commented May 4, 2018 at 14:49
  • Possible duplicate of Replacing objects in array Commented May 4, 2018 at 14:50
  • But getting that to work wasn't your problem, right? Commented May 4, 2018 at 14:50
  • 1
    Very nearly a duplicate of stackoverflow.com/questions/28961994/… (and the several others like it). Commented May 4, 2018 at 14:52

1 Answer 1

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});
}
Sign up to request clarification or add additional context in comments.

2 Comments

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: For that, you wouldn't use find, you'd use findIndex and then splice with the resulting index.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.