【问题标题】:How to check if the array of objects contains same value for a specific key如何检查对象数组是否包含特定键的相同值
【发布时间】:2020-10-13 16:34:57
【问题描述】:

我有以下对象数组:

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"
    }
]

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

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

【问题讨论】:

  • 你可以过滤你的数组
  • 你能举个例子吗?
  • var filter=array.filter(i=>i.environment==="ENV2"); console.log(filter.length?"has env 2":"all good")

标签: javascript arrays json typescript


【解决方案1】:

我认为你可以这样做:

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);

【讨论】:

    【解决方案2】:

    我会在这里使用过滤器:

    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')
    

    【讨论】:

    • 但他想比较 other_key 在数组的每个项目中是否有其他值。另外我认为在这里使用every 更合适,因为完全适合用例而不是过滤然后检查返回数组的length
    • 怎么回事?他写了Now I need to show an alert if the array has diifferent values for environment. If all environments are same, I don't need to show the alert.。我认为他想检查数组中的每个对象是否具有相同的 environment 属性值。
    猜你喜欢
    • 1970-01-01
    • 2023-03-08
    • 2015-06-24
    • 2019-01-12
    • 2010-12-13
    • 2022-08-18
    • 2016-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多