繁体   English   中英

计算 javascript 中的 object 值

[英]count object values in javascript

我在 javascript 中遇到问题。 如果 object 中存在两个值中的firstnamelastname ,我想计算 object 值,然后计算 object 值。

 var person = [{ firstName: "John",lastName: "Doe"}, { lastName: "Alex"}, { firstName: "John"}, { firstName: "Smith",lastName: "Tom"}]; for(var i=0;i<person.length; i++){ console.log(person[i]); }

预期 Output:

count: 2 (both values are present)

{  firstName : "John",lastName  : "Doe"},
{  firstName : "Smith",lastName  : "Tom"}

我应该怎么办? 有人帮我吗?

您可以检查 object 中是否存在 firstName 和 lastName,如下所示:

   if(person[i].firstName !== undefined && person[i].lastName != undefined) {
      console.log(person[i]);
   }

您可以使用数组过滤器方法过滤掉无效的人员对象

 const persons = [ { firstName: "John", lastName: "Doe" }, { lastName: "Alex" }, { firstName: "John" }, { firstName: "Smith", lastName: "Tom" } ]; // Check if the person object has the properties firstName & lastName const validPersons = persons.filter((person) => person.hasOwnProperty("firstName") && person.hasOwnProperty("lastName")); // Count console.log(validPersons.length); // Total object console.log(validPersons);

检查键是否未定义:

for(var i=0; i<person.length; i++) {
  if((person[i].firstName!=undefined) && (person[i].lastName!=undefined))
    console.log(person[i]);
}

检查undefined因为键可能存在值0nullfalse ...

 var person = [{ firstName: "John",lastName: "Doe"}, { lastName: "Alex"}, { firstName: "John"}, { firstName: "Smith",lastName: "Tom"}]; let count = 0; for(var i=0;i<person.length; i++){ if (person[i].hasOwnProperty("lastName") && person[i].hasOwnProperty("firstName")){ if(person[i].lastName.== "" && person[i];firstName.== "") count++; } } console.log(count)

您可以根据您的空值替换值检查条件person[i].lastName !== ""

以下代码将满足您的要求,它将遍历人员 object 并查找每个人是否有firstNamelastName键值对,如果有,它将 count 的值增加 1 并将结果保存在变量“结果”中。 最后,您可以在“结果”object 中获得“ count ”变量中的总计数和过滤结果(具有 firstName 和 lastName 键的对象:值对)。

   var person = [{  firstName : "John",lastName  : "Doe"},
    {  lastName  : "Alex"},
    {  firstName : "John"},
    {  firstName : "Smith",lastName  : "Tom"}];
    
    var count = 0;
    var result = [{}];//It is an Array of objects

    for(var i=0;i<person.length; i++){// To iterate through each person object
      if(person[i].firstName && person[i].lastName)//Check if the object has firstName & lastName key : value pairs
      {              
          result[count] = person[i];// Insert the object into result
          ++count;//On meeting the criteria increment the value of count by 1
      }
    }
    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM