2017-11-02 7 views
0

複雑なオブジェクトのプロパティ(配列を持つ入れ子オブジェクト)が存在するかどうかを確認する必要があります。 私はこの件に関していくつかの記事を見つけました。 提供されているソリューション(checkNested関数)の問題は、配列を持つオブジェクトでは機能しません。 誰もがこのケースをカバーするソリューションを持っていますか?配列を持つオブジェクトのオブジェクトキーの存在に関するJavascriptテスト

乾杯。

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"); 
+3

私たちが一緒に作業できる例はありますか? – Beau

+0

あなたが試したものとその配列を追加することができます。 –

+0

これまで試みたオブジェクトとコードのサンプルを投稿してください。 –

答えて

1

のTh使用している関数checkPropertyは角括弧([および])を認識しません。ドットのみを認識します。だから、ちょうどそれに点を付けてください:

checkProperty(msg, 'features.keywords.0.text'); 
関連する問題