javascript对没有空值的对象数组中的对象进行计数

时间:2019-05-22 10:46:04

标签: javascript arrays javascript-objects

假设我们有一系列对象:

const data = [
  {
    firstName: "Bruce",
    lastName: "Wayne",
    address: "Arkham 6",
    id: "1",
  },
  {
    firstName: "Peter",
    lastName: "Parker",
     address: "LA 54",
    id: "2"
  },
  {
    firstName: "Tony",
    lastName: "Stark",
    address: null,
    id: "3"
  }
];

,并希望获得数组的长度,但不包括对具有空值的对象进行计数(在上面的示例中,这是地址属性为null的最后一个对象),因此上述示例的计数结果会是2。

objectsWithoutNull = data.reduce(function (r, a) {
    return r + +( a!== null);
}, 0);

我正在尝试用reduce方法,但是得到了0。 迭代中的问题在哪里?

6 个答案:

答案 0 :(得分:2)

您可以filter()数组,然后获取object values并检查includes是否为空。

const data = [
  {
    firstName: "Bruce",
    lastName: "Wayne",
    address: "Arkham 6",
    id: "1",
  },
  {
    firstName: "Peter",
    lastName: "Parker",
     address: "LA 54",
    id: "2"
  },
  {
    firstName: "Tony",
    lastName: "Stark",
    address: null,
    id: "3"
  }
];

const notNullable = data.filter(obj=>!Object.values(obj).includes(null));
console.log(notNullable)
console.log(notNullable.length)

有关Object Values Filter Includes

的更多信息

答案 1 :(得分:1)

减少数组,对于每个对象,使用Object.values()获取值,并使用Array.includes()检查其是否包含null值。用!取反包含的布尔结果,然后使用+运算符将其转换为数字。将数字添加到累加器。

const data = [{"firstName":"Bruce","lastName":"Wayne","address":"Arkham 6","id":"1"},{"firstName":"Peter","lastName":"Parker","address":"LA 54","id":"2"},{"firstName":"Tony","lastName":"Stark","address":null,"id":"3"}];

const result = data.reduce((r, o) => 
  r + +!Object.values(o).includes(null)
, 0);

console.log(result);

答案 2 :(得分:1)

一个选项是遍历a的对象值并测试该值是否等于null。如果我们发现null不会增加计数器。

const data = [
  {
    firstName: "Bruce",
    lastName: "Wayne",
    address: "Arkham 6",
    id: "1",
  },
  {
    firstName: "Peter",
    lastName: "Parker",
     address: "LA 54",
    id: "2"
  },
  {
    firstName: "Tony",
    lastName: "Stark",
    address: null,
    id: "3"
  }
];

let objectsWithoutNull = data.reduce(function (r, a) {
  let hasNull = false;
  const values = Object.values(a);
  values.map(v => {
    if (v === null) {
      hasNull = true;
    }
  });
  
  return r + !hasNull;
}, 0);

console.log(objectsWithoutNull);

答案 3 :(得分:1)

  objectsWithoutNull = data.reduce(function (r, a) {
        return r + +( Object.values(a).indexOf(null) == -1);
    }, 0); 

如果您要检查所有属性,这将起作用!

答案 4 :(得分:1)

您可以使用Array.prototype.every来检查所有值都不为空

var length = data.filter(i => Object.values(i).every(i => i !== null)).length

答案 5 :(得分:0)

如果您使用lodash。

const data = [
      {
        firstName: "Bruce",
        lastName: "Wayne",
        address: "Arkham 6",
        id: "1",
      },
      {
        firstName: "Peter",
        lastName: "Parker",
         address: "LA 54",
        id: "2"
      },
      {
        firstName: "Tony",
        lastName: "Stark",
        address: null,
        id: "3"
      }
    ];

const counter = _.filter(data, ({address}) => {return address != null}).length;
console.log(counter);