我有以下对象数组:
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"
}
]
现在,如果数组的环境值不同,则需要显示警报。如果所有环境都相同,则无需显示警报。在上面的示例中,我需要显示警告警报。
如何检查特定键的数组是否包含不同的值或具有相同的值?
答案 0 :(得分:2)
我认为您可以这样做:
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);
答案 1 :(得分:0)
我只在这里使用过滤器:
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')