简体   繁体   English

如何通过对象键推送和替换数组中的值

[英]How to Push and Replace Value in Array by Object Key

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. 我想知道是否可以将对象推送到数组,并且id data-seats已存在,请在下次单击时替换/覆盖值。

Code: 码:

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

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. 我想知道是否可以将对象推送到数组,并且id数据座是否已存在,请在下次单击时替换/覆盖值。

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. 一个对象(使用Object.create(null)创建,因此它不继承任何属性)或Map是一个更好的选择。 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 这些工作,因为如果data-seats上没有active_filters对象/地图, active_filters["data-seats"] / active_filters.get("data-seats")undefined ,并且undefined || 0 undefined || 0 is 0 . undefined || 00 (Then we add 1 to it, and set the new value.) (然后,向其添加1,然后设置新值。)

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: 但是,您可以使用数组来执行此操作:使用find查看对象是否已经存在,如果存在,则对其进行更新;如果不存在,则进行添加:

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});
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM