根据条件获取对象数

问题描述 投票:2回答:6

我有一个包含一堆相似对象的对象。我只想获取对象属性(状态)具有给定值(true)的对象的计数。例如,以下对象的计数为3。

{
 6:{"name":"Mary", "status":true},
 2:{"name":"Mike", "status":true},
 1:{"name":"John", "status":false},
 4:{"name":"Mark", "status":true},
 5:{"name":"Jane", "status":false}
}

谢谢

javascript
6个回答
6
投票

我认识到您正在遍历一个对象,而不是数组,但是由于其他对象为数组提供了解决方案,因此我使用array.reduce解决了这个问题。适用于大多数现代浏览器(IE9 +)

var myArray = [
 {"name":"Mary", "status":true},
 {"name":"Mike", "status":true},
 {"name":"John", "status":false},
 {"name":"Mark", "status":true},
 {"name":"Jane", "status":false}
];

var result = myArray.reduce(function(previousValue, currentObject){
    return previousValue + (currentObject.status ? 1: 0); 
}, 0);

1
投票

特定:

var i = 0;
var count = 0;
while (i < array.length) {
    if (array[i]['status'] == true) count += 1; 
    i += 1;
}

更一般而言,您可以使用一些函数式编程:

function count_matches(array, func) {
    var i = 0;
    var count = 0;
    while (i < array.length) {
        if (func(array[i])) count += 1;
        i += 1;
    }
    return count;
}

function status_true(obj) {
    return obj['status'] == true;
}

count_matches(array, status_true);

上面的代码片段做同样的事情,但是后者更灵活/可能更整洁。


0
投票

仅循环遍历数组,并计数status属性为true的次数。

var count = 0;
for (var i = 0; i < yourArray.length; i++){
   var current = yourArray[i];
   if (current.status) count++
}

0
投票

LinqJs可以工作(对于问题中发布的简单示例来说可能太多了-

http://linqjs.codeplex.com/

var jsonArray = [
{ "user": { "id": 100, "screen_name": "d_linq" }, "text": "to objects" },
{ "user": { "id": 130, "screen_name": "c_bill" }, "text": "g" },
{ "user": { "id": 155, "screen_name": "b_mskk" }, "text": "kabushiki kaisha" },
{ "user": { "id": 301, "screen_name": "a_xbox" }, "text": "halo reach" }]


// ["b_mskk:kabushiki kaisha", "c_bill:g", "d_linq:to objects"]
var queryResult = Enumerable.From(jsonArray)
.Where(function (x) { return x.user.id < 200 })
.OrderBy(function (x) { return x.user.screen_name })
.Select(function (x) { return x.user.screen_name + ':' + x.text })
.ToArray();

// shortcut! string lambda selector
var queryResult2 = Enumerable.From(jsonArray)
.Where("$.user.id < 200")
.OrderBy("$.user.screen_name")
.Select("$.user.screen_name + ':' + $.text")
.ToArray();

0
投票
var obj = {
 6:{"name":"Mary", "status":true},
 2:{"name":"Mike", "status":true},
 1:{"name":"John", "status":false},
 4:{"name":"Mark", "status":true},
 5:{"name":"Jane", "status":false}
};
var count = 0;
for (var prop in obj) {
  if(obj[prop].status === true){
   count += 1; 
  }
}
console.log("Output: "+count);
$("#debug").text("Output: "+count);

实时演示http://jsbin.com/uwucid/2/edit


0
投票

a=[{"name":"Mary", "status":true},{"name":"Mike", "status":true},{"name":"John", "status":false},{"name":"Mark", "status":true},{"name":"Jane", "status":false}]
result=a.filter((e)=> e.status==true)
console.log(result)
© www.soinside.com 2019 - 2024. All rights reserved.