简体   繁体   English

如何将多个对象转换为单个数组并计算javascript中对象的长度?

[英]How to convert multiple objects to a single array and count the length of the objects in javascript?

I have this code:我有这个代码:

               {bloodStores &&
                  bloodStores.map((store) => {
                    if (
                      store.status === "Stock" &&
                      store.blood_component === "Whole Blood" &&
                      store.blood_group === "O+"
                    ) {
                      {
                       {' display the length of objects '}
                      }
                    }
                  })}

bloodStores is an array that holds too much data. BloodStores是一个包含过多数据的数组。 I looped and I filtered by getting the specific things I want as the above code.我循环并通过获取我想要的特定内容作为上述代码进行过滤。

After filtered I got the exact things I needed and all are objects like bellow code:过滤后,我得到了我需要的确切内容,并且都是像波纹管代码这样的对象:

 {
    "donor": "caamir yusuf ali",
    "hb": "18.13",
    "blood_group": "O+",
    "blood_component": "Whole Blood",
    "unit": "500",
    "bag": "K020068931",
    "status": "Stock"
  },
  {
    "donor": "zakariye mohamed adan",
    "hb": "16.71",
    "blood_group": "O+",
    "blood_component": "Whole Blood",
    "unit": "500",
    "bag": "K02059689",
    "status": "Stock"
  },
  {
    "donor": "cabdirashid colaad hassan",
    "hb": "17.55",
    "blood_group": "O+",
    "blood_component": "Whole Blood",
    "unit": "250",
    "bag": "EE559895",
    "status": "Stock"
  }

as you see the total of objects are 3 but how do I display that number????如您所见,对象总数为 3,但如何显示该数字????

You should do the filtering beforehand and then you can simply render the filtered items or the length of the resulting array.您应该事先进行过滤,然后您可以简单地呈现过滤后的项目或结果数组的长度。 There is no need to do that in jsx:在 jsx 中不需要这样做:

const availableZeroPositiveWholeBlood = bloodStores.filter(
    ({status, blood_component, blood_group}) => (
        status === "Stock" 
        && blood_component === "Whole Blood" 
        && blood_group === "O+"
    )
)

return <p>{availableZeroPositiveWholeBlood.length}</p>;

You should first use filter method to get a new array with the object that you are interested in and then use length property of an array.您应该首先使用filter方法获取一个包含您感兴趣的对象的新数组,然后使用数组的length属性。

\\ before you return from your component, filter out the array
const filteredBloodStores = bloodStores.filter(store => (store.status === "Stock" 
    && store.blood_component === "Whole Blood" 
    && store.blood_group === "O+"));

\\ and in your render, you can get length of that array
filteredBloodStores.length

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

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