遍历并计数数组内对象的对象

时间:2018-10-09 10:47:00

标签: javascript arrays object

我正试图返回一些住在瓦伦西亚的人。

例如,下面的arr返回2。

const arr = [
      { name: 'Cassandra', lives: { country: 'Spain', city: 'Valencia' }, age: 32.5 },
      { name: 'Cassandrella', lives: { country: 'Spain', city: 'Valencia' }, age: 35.55 }
    ]

我在访问对象以及遍历数组内部对象内的对象时遇到麻烦。这是我到目前为止获得的代码。我知道我在某个地方出错了,但似乎无法解决。

function countPeopleInValencia(people) {
  var count = 0;
   for (var i = 0; i = people.length; i++) {
     if (people[i].lives.city === 'Valencia') {
      count++;
     }
   }
   return count;                                 
}

3 个答案:

答案 0 :(得分:1)

您需要检查一下for语句的第二个参数。

for (var i = 0; i < people.length; i++) {
//              ^^^^^^^^^^^^^^^^^         check

function countPeopleInValencia(people) {
    var count = 0;
    for (var i = 0; i < people.length; i++) {
        if (people[i].lives.city === 'Valencia') {
            count++;
        }
    }
    return count;
}

const arr = [{ name: 'Cassandra', lives: { country: 'Spain', city: 'Valencia' }, age: 32.5 }, { name: 'Cassandrella', lives: { country: 'Spain', city: 'Valencia' }, age: 35.55 }];

console.log(countPeopleInValencia(arr));

答案 1 :(得分:1)

function countPeopleInValencia(people) {
    return people.filter(p => p.lives.city === 'Valencia').length;
}

const arr = [
    { name: 'Cassandra', lives: { country: 'Spain', city: 'Valencia' }, age: 32.5 },
    { name: 'Cassandrella', lives: { country: 'Spain', city: 'Valencia' }, age: 35.55 }
]


console.log(countPeopleInValencia(arr))

答案 2 :(得分:1)

它可以是一根班轮

arr.filter(function(o){return o.lives.city==="Valencia"}).length

$.map(arr,function(o){return o.lives.city==="Valencia"}).length