3 回答
TA贡献1831条经验 获得超9个赞
如果要检查数组是否包含至少一个具有特定属性的对象,可以使用 some
找到属性的示例:
var data = [{
"Global Quote": {}
}]
data.some(o => "Global Quote" in o) ? console.log("found") : console.log("not found ");
未找到属性的示例:
var data = [{
"Not Global Quote": {},
},
{
"Not Global Quote Also": {},
}
]
data.some(o => "Global Quote" in o) ? console.log("found") : console.log("not found ");
TA贡献1777条经验 获得超3个赞
假设您将在该数组中拥有多个对象,您可以使用some.
const data = [{
"Global Quote": {
"01. symbol": "TSLA",
"02. open": "256.7100",
"03. high": "260.4800",
"04. low": "254.5100",
"05. price": "260.1700",
"06. volume": "4967930",
"07. latest trading day": "2019-07-23",
"08. previous close": "255.6800",
"09. change": "4.4900",
"10. change percent": "1.7561%"
}
}];
function findKey(arr, key) {
return arr.some(obj => Object.keys(obj)[0] === key);
}
console.log(findKey(data, 'Global Test'));
console.log(findKey(data, 'Global Quote'));
TA贡献1817条经验 获得超6个赞
在检查带有data.includes(...).
您必须更深入一层并使用hasOwnProperty方法检查属性。
您的代码将如下所示:
const data = [{
"Global Quote": {
"01. symbol": "TSLA",
"02. open": "256.7100",
"03. high": "260.4800",
"04. low": "254.5100",
"05. price": "260.1700",
"06. volume": "4967930",
"07. latest trading day": "2019-07-23",
"08. previous close": "255.6800",
"09. change": "4.4900",
"10. change percent": "1.7561%"
}
}]
data[0].hasOwnProperty('Global Quote') ? console.log('found') : console.log('not found);
添加回答
举报