我有一个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);
答案 0 :(得分:3)
使用Array#some
检查至少一个元素是否具有status
属性active
属性。
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;
答案 1 :(得分:1)
您将response
设置为true
,不要中断循环,然后在遇到其他值时再次将其设置为false
。
您可能只是设置初始条件,然后找到项目时break
。当你找到一个项目时,你甚至可以不破坏,但是当找到一个项目时继续迭代是没用的。
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;
另一种优雅的方法是使用功能并使短路返回:
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;
请注意,出于某种原因,您已.len
,我已将其替换为正确的.length
。
更优雅的方法是使用 Array.prototype.some
:
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;
答案 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);