javascript数组对象逻辑中的小问题

时间:2017-03-09 11:47:39

标签: javascript arrays node.js

我有一个json数组如下所示。如果我发现至少有一个状态为Active的对象我需要设置response = true或者false。我试过下面但是没有用。可以帮助。

arr=[{"id":"1","status":"active"},{"id":"2","status":"complete"},
{"id":"3","status":"complete"}]
for (var i = 0; i < arr.len; i++) {                          
    if (arr[i].status == "active") {
        response = true;
    } else {
        response = false;
    }
}
console.log(response);

3 个答案:

答案 0 :(得分:3)

使用Array#some检查至少一个元素是否具有status属性active属性。

&#13;
&#13;
var arr = [{"id":"1","status":"active"},{"id":"2","status":"complete"},
{"id":"3","status":"complete"}],
    response = arr.some(v => v.status == 'active');
    console.log(response);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您将response设置为true,不要中断循环,然后在遇到其他值时再次将其设置为false

您可能只是设置初始条件,然后找到项目时break 。当你找到一个项目时,你甚至可以不破坏,但是当找到一个项目时继续迭代是没用的。

&#13;
&#13;
var arr = [{
    "id": "1",
    "status": "active"
  }, {
    "id": "2",
    "status": "complete"
  },
  {
    "id": "3",
    "status": "complete"
  }
];

var response = false;
for (var i = 0; i < arr.length; i++) {
  if (arr[i].status == "active") {
    response = true;
    break;
  }    
}

console.log(response);
&#13;
&#13;
&#13;

另一种优雅的方法是使用功能并使短路返回

&#13;
&#13;
var arr = [{
    "id": "1",
    "status": "active"
  }, {
    "id": "2",
    "status": "complete"
  },
  {
    "id": "3",
    "status": "complete"
  }
];

function hasActiveStatus(a) {
  for (var i = 0; i < a.length; i++) {
    if (a[i].status == "active") {
      return true;
    } 
  }
  
  return false;
}

var response = hasActiveStatus(arr);
console.log(response);
&#13;
&#13;
&#13;

请注意,出于某种原因,您已.len,我已将其替换为正确的.length

更优雅的方法是使用 Array.prototype.some

&#13;
&#13;
var arr = [{
    "id": "1",
    "status": "active"
  }, {
    "id": "2",
    "status": "complete"
  },
  {
    "id": "3",
    "status": "complete"
  }
];

var response = arr.some(function(x) { return x.status === "active"; });
console.log(response);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

var response = false;
var arr=[{"id":"1","status":"active"},{"id":"2","status":"complete"},
{"id":"3","status":"complete"}]
for (var i = 0; i < arr.length; i++) {                          
    if (arr[i].status == "active") {
        response = true;
        break;
    } 
}
console.log(response);