从深层对象中检索值

时间:2016-12-19 07:18:52

标签: javascript

我试图从对象中获取值,但我无法得到它。 我得到的最大值是that,have console.log(randomWords)

我确定我在这里做错了什么,但我已经花了很长时间试图找到错误。该对象看起来很好,我无法找到一种方法来访问这些深层值。

  var words = {
      "that": {
         "languages": {
            "pt": {
               "multiple_meanings": true,
               "meaning": ["aquilo", "aquela"]
            },
            "it": {
               "multiple_meanings": false,
               "meaning": "quella"
            }
         }
      },
      "this": {
         "languages": {
            "pt": {
                "multiple_meanings": true,
                "meaning": ["este", "esta"]
            },
            "it": {
                "multiple_meanings": true,
                "meaning": ["questo", "questa"]
            },
          }
        }
    };
    var userChoseLanguage = "pt"
    var wordsKeysArr = Object.keys(words).toArray; 
    var wordIndex = Math.floor(Math.random() * wordsKeysArr.length);

    //store a random word in randomWord
     var randomWord = recipesKeysArr[factIndex];

    //if user chose pt
     if(userChoseLanguage == "pt"){
        //if multiple_meanings = true
        if(randomWord.languages.multiple_meanings===true) {
           console.log("This word has more than one meaning");
        }
        else {
           console.log(randomWord.languages.meaning);
        }
     }

1 个答案:

答案 0 :(得分:0)

" recipesKeysArr [factIndex]"仅返回基于索引而不是整个对象的值。

因此,您可以将其用作索引来访问"单词"中的特定对象。

if (userChoseLanguage == "pt") {
    //if multiple_meanings = true
    if (words[randomWord].languages[userChoseLanguage].multiple_meanings === true) {
        console.log("This word has more than one meaning");
    }     
    else {
        console.log(words[randomWord].languages[userChoseLanguage].meaning);
    }
}