简体   繁体   中英

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

...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. Usually I'd create an Array with all the Ids by

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

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

This will contain all the IDs in the array.

Now, to remove those <option> s whose value is not in the above array, you can create a selector from the array.

$('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.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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