如何检查JS对象数组中包含的适当属性?
const array=[
{ name: "A", hasCar: true},
{ name: "B" }
];
// if (array has "hasCar") {
// do something
// }
我想确定数组是否具有"hasCar"
。
array.includes
不适用于对象数组。
我应该使用.hasOwnProperty("hasCar")
还是其他解决方案?
答案 0 :(得分:0)
您可以拿Array#some
并与Object.hasOwnProperty
核对。
const array = [{ name: "A", hasCar: true}, { name: "B" }];
console.log(array.some(o => o.hasOwnProperty('hasCar')));