jQuery第一个对象,其中x = true

时间:2015-08-28 14:06:46

标签: jquery object each

我有一些对象作为参数传递给函数,例如:

$( document ).on( "custom.event", function( evt, obj ) {
    console.log( obj );
});

对象看起来像这样(在控制台中):

Object {name: "obj1", property: "", somethingElse: "some value"}
Object {name: "obj2", property: "1", somethingElse: "some value"} //I want this one!
Object {name: "obj3", property: "", somethingElse: "some value"}
Object {name: "obj4", property: "1", somethingElse: "some value"}

我想利用属性等于“1”的FIRST对象,并拥有剩余的属性及其值(来自所述obj)。我怎么能这样做?我已经尝试了$ .each,但无法解决如何只返回属性==“1”的第一个对象。

由于

3 个答案:

答案 0 :(得分:2)

您可以使用$.each循环遍历元素,并在找到第一个对象时使用override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? { var shareAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Aceitar" , handler: {(action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in // Put your shareAction handler stuff here }) var rateAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Recusar" , handler: {(action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in // Put your rateAction handler stuff here }) shareAction.backgroundColor = UIColor.redColor() rateAction.backgroundColor = UIColor.blueColor() return [shareAction, rateAction] } 来打破循环:

return false

如果您不担心IE8或更低版本,您也可以使用Array.prototype.filter()

var searchedObject = null;
$.each(obj, function(index, el) {
    if (el.property == "1") {
        searchedObject = el;
        return false;
    }
});

答案 1 :(得分:1)

在项目与所需的属性值匹配时,遍历数组并存储引用。

var first1Obj;

for(i=0; i<=obj.length; i++){
   if (obj[i].property == "1"){
       first1Obj = obj[i];
       break;
    }
}

请参阅演示:http://jsfiddle.net/7vmbs95t/

答案 2 :(得分:1)

检查这是否适合您:https://jsfiddle.net/leojavier/83wt0vvg/

var obj = [
 {name: "obj1", property: "", somethingElse: "some value"},
 {name: "obj2", property: "1", somethingElse: "some value"},
 {name: "obj3", property: "", somethingElse: "some value"},
 {name: "obj4", property: "1", somethingElse: "some value"}]

 for(item in obj) {
  if(obj[item].property == 1) {
    console.log(obj[item].name)
    break;
  }

 }