Using jQuery inArray with array of JavaScript Obje

2020-01-28 06:22发布

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 appreciated. 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.

5条回答
三岁会撩人
2楼-- · 2020-01-28 07:05

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

$.grep(issuesArray, function(n) { return n.ID != "2"; })
查看更多
倾城 Initia
3楼-- · 2020-01-28 07:15

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++]);
  }
}
查看更多
姐就是有狂的资本
4楼-- · 2020-01-28 07:20

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);
});
查看更多
神经病院院长
5楼-- · 2020-01-28 07:20
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));
查看更多
家丑人穷心不美
6楼-- · 2020-01-28 07:25

Simplify??

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

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

查看更多
登录 后发表回答