gpt4 book ai didi

Javascript 测试带有数组的对象中是否存在对象键

转载 作者:行者123 更新时间:2023-12-03 03:08:11 25 4
gpt4 key购买 nike

我需要检查复杂对象(带有数组的嵌套对象)中的属性是否存在。我发现了几篇关于这个主题的帖子,下面是访问量最大的一篇。所提供的解决方案(checkNested 函数)的问题不适用于具有数组的对象。有人有解决这个问题的解决方案吗?

干杯。

javascript test for existence of nested object key

这是我测试的功能:

function checkProperty(obj, prop) {
var parts = prop.split('.');
for (var i = 0, l = parts.length; i < l; i++) {
var part = parts[i];
if (obj !== null && typeof obj === "object" && part in obj) {
obj = obj[part];
} else {
return false;
}
}
return true;
}

这是我的对象的示例:

{
"_msgid": "3ae30deb.af9962",
"topic": "",
"payload": "I am really upset terrible service",
"error": null,
"parts": {
"id": "3ae30deb.af9962",
"type": "array",
"count": 2,
"len": 1,
"index": 0
},
"case_id": "0001",
"features": {
"usage": {
"text_units": 1,
"text_characters": 34,
"features": 7
},
"sentiment": {
"document": {
"score": -0.912124,
"label": "negative"
}
},
"semantic_roles": [{
"subject": {
"text": "I"
},
"sentence": "I am really upset terrible service",
"object": {
"text": "really upset terrible service",
"keywords": [{
"text": "terrible service"
}]
},
"action": {
"verb": {
"text": "be",
"tense": "present"
},
"text": "am",
"normalized": "be"
}
}],
"language": "en",
"keywords": [{
"text": "terrible service",
"sentiment": {
"score": -0.912124
},
"relevance": 0.902721,
"emotion": {
"sadness": 0.462285,
"joy": 0.002207,
"fear": 0.125395,
"disgust": 0.17766,
"anger": 0.575927
}
}],
"entities": [],
"emotion": {
"document": {
"emotion": {
"sadness": 0.462285,
"joy": 0.002207,
"fear": 0.125395,
"disgust": 0.17766,
"anger": 0.575927
}
}
},
"concepts": [],
"categories": [{
"score": 0.99946,
"label": "/health and fitness/disease/headaches and migraines"
}, {
"score": 0.0155692,
"label": "/education/school"
}, {
"score": 0.0141217,
"label": "/family and parenting/children"
}]
}
}

以及失败测试:

console.log(checkProperty(msg, 'features.keywords[0].text') ? msg.features.keywords[0].text : "NA");

最佳答案

您使用的 checkProperty 函数无法识别括号([]),它只能识别点。所以,只需给它点:

checkProperty(msg, 'features.keywords.0.text');

关于Javascript 测试带有数组的对象中是否存在对象键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47072639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com