根据id从数组中删除项目

时间:2015-01-19 19:44:24

标签: javascript

我有两个数组。我需要展示的其中一个元素,然后是下拉列表中的另一个元素。如果id匹配,则显示。这听起来很简单,但我很难切出不需要显示的元素。

所以它看起来像这样

var option = //Ton of objects with values that match with the id that look like this, there are about 70 of them. I need to loop through these to get the value of each one. Please see screen shot, I don't know how else to show that they are objects.

enter image description here     var ids = [16,15,17,18,5];

然后我试图遍历每个选项,看看该值是否等于Id。出于某种原因,这将删除所有内容,而不仅仅是需要删除的内容。

for(var i=0 ; i<option.length; i++){
    if (option[i].value !== ids) { 
        option.splice(i);
    }
}

4 个答案:

答案 0 :(得分:2)

尝试过滤功能:

var newOptions = options.filter(function(option, index) {
     return ids.indexOf(option.value) >= 0;
});

var values = newOptions.map(function(option) {
    return option.value;
});

答案 1 :(得分:0)

如果您要从option数组中删除项目:

var option = [
    {display:'opt50', value:50 },
    {display:'opt16', value:16 },
    {display:'opt10', value:10 },
    {display:'opt17', value:17 },
    {display:'opt43', value:43 },
    {display:'opt5', value:5 }
]


var ids = [16, 15, 17, 18, 5];

for(var i = option.length - 1; i > -1; i--) {
    if(ids.indexOf(option[i].value) == -1) {
        option.splice(i,1);
    }
}

// logs [{"display":"opt16","value":16},{"display":"opt17","value":17},{"display":"opt5","value":5}]
console.dir(JSON.stringify(option));

如果您只想查找匹配的项目并保持option完好无损:

// fill in options with some elements
var option = [
    {display:'opt50', value:50 },
    {display:'opt16', value:16 },
    {display:'opt10', value:10 },
    {display:'opt17', value:17 },
    {display:'opt43', value:43 },
    {display:'opt5', value:5 }
]


var ids = [16, 15, 17, 18, 5];

var filteredOption = option.filter(function(o) {
    return ids.indexOf(o.value) > -1;
});

// logs [{"display":"opt16","value":16},{"display":"opt17","value":17},{"display":"opt5","value":5}]
console.dir(JSON.stringify(filteredOption));

答案 2 :(得分:-1)

!==运算符总是返回true。

12 !== [12,34,45]
true
13 !== [12,34,45]
true

因此,if (option[i].value !== ids) {将始终执行option.splice(i);,因为比较值始终为不同类型

Mozilla's Sameness documentation有一个很好的解释和有用的图表。

答案 3 :(得分:-1)

&#13;
&#13;
    var option = [{display: "Member Form",value: 2}, {display: "Member Form",value: 5}];

    var ids = [16, 15, 17, 18, 5];
    var optionKey = Object.keys(option);
    for(var i = optionKey.length - 1; i >= 0 ; i--){
       if (ids.indexOf(option[optionKey[i]].value) == -1) { 
           option.splice(i, 1) //second argument allows splice to only delete one element.
       }
    }
    console.log(option);
    document.write(JSON.stringify(option)); //result!
&#13;
&#13;
&#13;