简体   繁体   English

如何检查 Javascript 对象数组是否始终具有相同的值

[英]How to check if Javascript array of objects has the same value throughout

I have the following array:我有以下数组:
distributors = [{ Name: 'Foo', Count: 0}, { Name: 'Bar', Count: 0}, { Name: 'Baz', Count: 0}]

How do I check if the 'Count' is 0 for every object in the array?如何检查数组中每个 object 的“计数”是否为 0? Ideally, I would like to write a function to return boolean if the value for 'Count' is 0 for every object in the array.理想情况下,如果数组中每个 object 的“计数”值为 0,我想编写一个 function 以返回 boolean。

You can use every method.您可以使用每种方法。 Every method checks if all elements in an array pass a test and returns true or false based on the function you have provided.每个方法都会检查数组中的所有元素是否都通过了测试,并根据您提供的 function 返回 true 或 false。 So, If every element pass the test it returns true otherwise false.因此,如果每个元素都通过测试,则返回 true,否则返回 false。

 const distributors = [ { Name: 'Foo', Count: 0 }, { Name: 'Bar', Count: 0 }, { Name: 'Baz', Count: 0 }, ]; const ret = distributors.every((x) => x.Count === 0); console.log(ret);

This function returns true if all the Count property is 0如果所有 Count 属性为 0,则此 function 返回 true

function checkCount(distributors) {
    for (let element of distributors) {
        if (element.Count) {
            return false;
        }
    }

    return true;
}

暂无
暂无

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

相关问题 如何过滤对象数组并检查数组内是否有多个 object 在 Javascript 中具有相同的属性值? - How to filter array of objects and check if more than one object inside the array has the same property value in Javascript? 如何检查对象数组是否具有相同键的相同值? - How to check if array of objects has same value for same key? 如何获取具有相同属性的对象并在数组中具有最大值 - Javascript - how to get objects with the same property and has the max value in array - Javascript 如何根据JavaScript中的值检查对象是否在数组中? - How to check if objects are in an array based on a value in JavaScript? 在 javascript 如何在具有嵌套数组的对象数组中查找值 - In javascript how to find value in a array of objects that has a nested array 如何检查我推入对象的对象数组是否具有来自另一个对象数组的特定键值 - How to check if an array of objects where I push into objects has a specific key value from another array of objects 如何检查对象数组是否包含特定键的相同值 - How to check if the array of objects contains same value for a specific key 如何在 mongoDB 中检查对象数组中的 2 个元素是否具有相同的值? - How to check if 2 elements inside an array of objects have the same value, in mongoDB? 如何检查和分类json数组中的键是否具有相同的值? - How to check & classify if key in json array has same value? 如何检查变量是否具有与列表/数组中其他变量相同的值? - How to check if a variable has the same value as any other in a list/array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM