繁体   English   中英

如何检查对象数组是否包含特定键的相同值

[英]How to check if the array of objects contains same value for a specific key

我有以下对象数组:

const array = [
    {
        "id":1,
        "environment":"ENV1",
        "other_key":"other_value"
    },
    {
        "id":2,
        "environment":"ENV1",
        "other_key":"other_value_two"
    },
    {
        "id":3,
        "environment":"ENV2",
        "other_key":"other_value_three"
    }
]

现在,如果数组具有不同的环境值,我需要显示警报。 如果所有环境都相同,我不需要显示警报。 在上面的例子中,我需要显示警告警报。

如何检查数组是否包含特定键的不同值或是否具有相同的值?

我认为你可以这样做:

 const array = [ { "id":1, "environment":"ENV1", "other_key":"other_value" }, { "id":2, "environment":"ENV1", "other_key":"other_value_two" }, { "id":3, "environment":"ENV2", "other_key":"other_value_three" } ] const everyEnvHasSameValue = array.every( ({other_key}) => other_key === array[0].other_key); // use proper name console.log(everyEnvHasSameValue);

我只想在这里使用过滤器:

const array = [
    {
        "id":1,
        "environment":"ENV1",
        "other_key":"other_value"
    },
    {
        "id":2,
        "environment":"ENV1",
        "other_key":"other_value_two"
    },
    {
        "id":3,
        "environment":"ENV1",
        "other_key":"other_value_three"
    }
]

const el = array.filter(e => e.environment !== array[0].environment)
if(el.length > 0) alert('envs are diff')

暂无
暂无

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

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