简体   繁体   中英

Compare and Delete the items in jquery array objects

I am collecting a list of users for each request and pushing the list of users into arrays like below:

$.each(data, function (i, item) {
    jQuery.each(array, function (index, data) {
        if (data.UserId == user.Id) {
            //do nothing
        }
    });

    else{
        array.push(UserId:user.Id);
    }

});

Then, I am sending these data to the server:

jQuery.ajax({
    cache: false,
    type: "GET",
    url: "Handler.ashx",
    contentType: "application/json; charset=utf-8",
    data: { UsersData: JSON.stringify(array) },
    dataType: "json"
});

Now at next time, I have to find the object as previous and to delete the users who are not presented in users list and I have to send into request. Please can any one tell me how to add the list of users into array and to delete the users from array who are not in list of users.

If you have an array of data that you want to remove some off you can use the jQuery filter method ( source ) or even better the Array's filter method ( source ).

Note: The Array filter method (along with map, reduce and a few others) are part of ECMAScript 5 and aren't supported in some of the older browsers (basically the older IEs). There are plenty of shim out there though and the mdn docs all show how to implement the methods yourself ( but here's a good shim if you want them all ).

Here's how you'd use it:

var array = [1,2,3,4,5,6];
var filteredArray = array.filter(function (item /*current item in the array*/) {
    return item % 2; //return a boolean
});
console.log(filteredArray); // [1,3,5]

You then have a subset you can pass into your AJAX method.

JavaScript offers several ways to easily add to or remove from arrays.

// add "7" to the array
var nums = [1,2,3,4,5,6];
nums.push(7);

// remove "3" from the array (index position #2)
nums.splice(2,1);

// find "5" and remove it
nums.splice(nums.indexOf(5), 1);

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