将 jQuery inArray 与 JavaScript 对象数组一起使用 [英] Using jQuery inArray with array of JavaScript Objects

查看:24
本文介绍了将 jQuery inArray 与 JavaScript 对象数组一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一组 JavaScript 对象:

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"}];

当我知道对象的 ID 时,我的最终努力是尝试从数组中删除一个对象.我正在尝试使用类似这样的代码:

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);
});

所以这表明我正在尝试使用 jQuery grep 通过索引 (i) 删除元素,我正在尝试使用 jQuery inArray 检索该元素.当然上面的代码是行不通的,因为2"应该对应数组中的一个项目,它们都是JavaScript对象(一个对象永远不会等于2").我需要类似的东西:

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);

有没有人成功地使用 inArray 获取 JavaScript 对象的索引,并使用该对象中的字段值?任何帮助,将不胜感激.谢谢.

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";
});

我想我想得太深了,当时解决方案真的很简单.我只是想从数组中删除一个 JavaScript 对象,只要我知道该对象中特定属性的值.上述解决方案使用 jQuery 的 grep 从数组中返回除 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 是你的列表项,所以这样的事情应该可以完成:

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

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

这篇关于将 jQuery inArray 与 JavaScript 对象数组一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆