简体   繁体   中英

How to simplify this delete from array jQuery

I have an object and an array of categories that should be kept in the object. This snip https://jsfiddle.net/h10rkb6s/2/ ( see log ) works but I cant seems to shake the idea that it is to complicated for a simple search and keep task.

var thz_icon_source = {"Spinners":["spinnericon1","spinnericon2"],"Awesome":["awesomeicon1","awesomeicon2"],"Others":["othericon1","othericon2"]};
var $categories = '["Spinners","Awesome"]';

var $CatsArray = JSON.parse($categories);
var groups = [];
for(var k in thz_icon_source) groups.push(k);



$.each($CatsArray,function(i,keep){

    var index = groups.indexOf(keep);
    if (index !== -1) {
        groups.splice(index, 1);
    }               

});

for (var i = 0; i < groups.length; i++) {
    delete thz_icon_source[groups[i]];
}

I tried with

   $.each(thz_icon_source,function(category,icons){

            $.each($CatsArray,function(i,keep){

                var index = category.indexOf(keep);

                if (index !== -1) {
                    delete thz_icon_source[category];
                }                   

            });

        });

but this works only if 1 item is inside my search array. Any help is appreciated.

There's no need to iterate over $CatsArray to find out which ones should be deleted. You will need to iterate over the keys of the object, and find out for each of them whether it should be deleted, to filter by that.

Leaving the top 3 lines of your script intact, you could simplify to

var keysToDelete = Object.keys(thz_icon_source).filter(function(groupName) {
    return $CatsArray.indexOf(groupName) == -1;
});

( $.grep would be the jQuery-ism for the filter method, if you are into that).

But assuming we don't even need those groups in an array, you could simply do

for (var groupName in thz_icon_source)
    if ($CatsArray.indexOf(groupName) == -1)
        delete thz_icon_source[groupName];

However, instead of deleting items from that object, I'd recommend to create a new object with only those that you want to keep. It's much easier to use:

var kept = {};
for (var i=0; i<$CatsArray.length; i++)
    kept[$CatsArray[i]] = thz_icon_source[$CatsArray[i]];

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