简体   繁体   English

jQuery-检查值是否存在于关联数组的列中

[英]Jquery - checking if value exist in a column of an associative array

I want to check if the an id already exist in my array. 我想检查ID是否已存在于我的数组中。 if It exists the older value should be removed, and the new value should be added to the array, if not it should be added to the array. 如果存在,则应删除较旧的值,并应将新值添加到数组中;如果不存在,则应将其添加到数组中。

Here's the code that I tried but didn't work. 这是我尝试但无法正常工作的代码。

sample_array[0] = {'id' : 1, 'letter': 'a'};
sample_array[1] = {'id' : 2, 'letter': 'b'};
sample_array[2] = {'id' : 3, 'letter': 'c'};
sample_array[3] = {'id' : 4, 'letter': 'd'};
sample_array[4] = {'id' : 5, 'letter': 'e'};

input_id = 3;
count_length = sample_array.length;
input_letter = 'L'; 
idx = $.inArray(input_id, sample_array.id); // <- i think this is where it goes wrong.

if(idx ==  -1)
{
   //add to the array
   sample_array[count_length] = {'id' : input_id, 'letter': input_letter};              
}
else
{
   //remove then add to the array
   sample_array.splice(idx, 1);
   sample_array[count_length] = {'id' : input_id, 'letter': input_letter}; 
}

You are searching for a primitive value not an object, so 您要搜索的是原始值而不是对象,因此

replace from this line onwards 从此行开始替换

idx = $.inArray(input_id, sample_array.id);

with

sample_array.forEach(function(value,index){
   if(value.id==input_id)
   {
     sample_array.splice(index,1);
   }
}).length;
sample_array.push({'id' : input_id, 'letter': input_letter});

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

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