如何检查数组中是否存在特定的对象元素(不是属性)?

我尝试使用 .includes() 方法,但我无法让它工作。


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.includes("Global Quote") ? console.log("found") : console.log("not 

found");

控制台每次都记录“未找到”...


LEATH
浏览 151回答 3
3回答

天涯尽头无女友

如果要检查数组是否包含至少一个具有特定属性的对象,可以使用 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 ");

慕森王

假设您将在该数组中拥有多个对象,您可以使用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'));

慕的地6264312

在检查带有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);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript