简体   繁体   English

将结果从Ajax-Request传输到数组的更简洁方法

[英]Slimmer way to transfer results from an Ajax-Request to an array

I'm currently having this situation. 我目前正处于这种情况。 I'm getting a response from an AJAX-call like this 我收到了像这样的AJAX调用的响应

...responseJSON.d.results : [
    {
        "Title" : "SomeTitle",
        "Id" : 1
    },
    {
        "Title" : "SomeOtherTitle",
        "Id"    : 2
    }
]

Now I want to go through options in my DOM and check if the Value-Attributes are part of my Ids in the request. 现在我想通过我的DOM中的选项来检查Value-Attributes是否是请求中我的Ids的一部分。 Usually I'd create an Array with all the Ids by 通常我会创建一个包含所有ID的数组

var ids = [];
$.each(response.JSON.d.results, function(){
    ids.push(this.Id)
});

After that I would iterate through the options and remove them if the attributes are not found in the array like 之后,如果在数组中找不到属性,我会遍历选项并删除它们

$.each($('option.someClass'), function(){
    if(ids.indexOf(parseInt($(this).attr('value'))) === -1) $(this).remove()
});

However I found that to be a little unelegant. 但是我发现它有点不太优雅。 I was wondering if there maybe was a slimmer way to do this. 我想知道是否有更轻薄的方法来做到这一点。 Would appreciate the help. 很感激帮助。

To get the IDs from the array, you can use Array#map 要从数组中获取ID,可以使用Array#map

var ids = response.JSON.d.results.map(o => o.Id);

This will contain all the IDs in the array. 这将包含数组中的所有ID。

Now, to remove those <option> s whose value is not in the above array, you can create a selector from the array. 现在,要删除其value不在上面数组中的<option> ,可以从数组中创建一个选择器。

$('option.someClass')
    .not('option[value="' + ids.join('"].someClass, option[value="') + '"].someClass')
    .remove();

The string concatenation and array join will give the selector in the format 字符串连接和数组连接将以格式提供选择器

"option[value="1"].someClass, option[value="2"].someClass, option[value="3"].someClass"

which can directly used with jQuery. 它可以直接与jQuery一起使用。

 var arr = [{ "Title": "SomeTitle", "Id": 1 }, { "Title": "SomeOtherTitle", "Id": 2 }]; var ids = arr.map(o => o.Id); $('option.someClass') .not('option[value="' + ids.join('"].someClass, option[value="') + '"].someClass') .remove(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select> <option value="1" class="someClass">1</option> <option value="2" class="someClass">2</option> <option value="3" class="someClass">3</option> <option value="4" class="someClass">4</option> <option value="5" class="someClass">5</option> </select> 

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

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