开发者

Using jQuery inArray with array of JavaScript Objects

I'm working with an array of JavaScript Objects as such:

var IssuesArray = [{"ID" : "1", "Name" : "Issue1"}, 
                   {"ID" : "2", "Name" : "Issue2"}, 
                   {"ID" : "3", "Name" : "Issue3"}];

My end effort is trying to remove an object from the array when I know the ID of the object. I'm trying to use code that is something like this:

$.grep(IssuesArray, function(n, i) {
    return i != $.inArray("2", IssuesArray);
});

So this shows that I'm trying to use jQuery grep to remove an element by index (i), which I am trying to retrieve by using jQuery inArray. Of course the code above will not work because "2" should correspond to an item in the array, which are all JavaScript objects (an object will never equal "2"). I need something like:

$.inArray(javascriptObject.Name=="2", IssuesArray);

Has anyone ever had any success using inArray to get indexes of JavaScript objects, using a field value within that object? Any help would be appre开发者_Python百科ciated. Thanks.

UPDATE/CLARIFICATION: A couple people have been confused by my question, but I received an answer that works nonetheless. I'm using:

IssuesArray = $.grep(IssuesArray, function(n) {
    return n.ID != "2";
});

I think I was thinking about it too deep, when the solution was really pretty easy. I simply wanted to remove a JavaScript object from an array, so long as I knew a particular property's value in that object. The above solution uses jQuery's grep to return everything from the array except any object whose ID == "2". As usual, thanks for the quick answers. A couple answers were good solutions and would have worked using (using "splice", for example), but this solution seems to be the shortest most straightforward. Thanks again.


n is your list item, so something like this should do the job:

$.grep(issuesArray, function(n) { return n.ID != "2"; })


Not sure if I understood your question correctly, but I would do:

$.each(IssuesArray, function(i, item){
  if (item.ID == IDToBeRemoved) IssuesArray.splice(i, 1);
});


var spliceID = function(id, arr) {
    $(arr).each(function(i, el) {
        if (el.ID == id) {
            arr.splice(i,1);
            return false;
        }
    });
    return arr;
}

console.log(spliceID('2', IssuesArray));


Without using jQuery or other frameworks:

var newArray = [];
var i=0, len=IssuesArray.length;
var bad_id = "2"; // or whatever
while(i<len) {
  if(IssuesArray[i].ID !== bad_id) {
    newArray.push(IssuesArray[i++]);
  }
}


Simplify??

var IssuesArray = {
  1: "Issue1",
  2: "Issue2", 
  3: "Issue3"
};
var issue2 = IssuesArray[2];

Why a list of hashes when a single hash will do?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜