在具有对象的数组中,检查这些对象中是否存在键 [英] In an array with objects, check if a key exists in any of those objects
本文介绍了在具有对象的数组中,检查这些对象中是否存在键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个对象数组,需要查看其中是否存在键.这是我现在正在做的事情:
I have an array of objects, and need to see if a key exists in any of them. Here is what I am doing now:
const arr = [{ id: 1, foo: 'bar' }, { id: 2 }]
arr.map(o => o.foo && true).includes(true)
// true
是否有更好/更被接受的方式来做到这一点?
Is there any better/more accepted way to do this?
推荐答案
const arr = [
{ id: 1, foo: 'bar' },
{ id: 2 }
];
var result = arr.some(e => e.hasOwnProperty('foo'));
console.log("The array contains an object with a 'foo' property: " + result);
var result = arr.some(e => e.hasOwnProperty('baz'));
console.log("The array contains an object with a 'baz' property: " + result);
这篇关于在具有对象的数组中,检查这些对象中是否存在键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文