2017-02-15 136 views
-2

我需要關鍵的country_code和language_code的值。如何獲取數組內的JavaScript對象中的鍵的值?

我已經試過

sourceLanguageArray[0].$.country_code; 
sourceLanguageArray[0].$.language_code; 

我得到的錯誤:

console.log(sourceLanguageArray[0].$.country_code); 
      ^
ReferenceError: sourceLanguageArray is not defined 

這是數據結構的代碼和控制檯日誌的樣子:

source_language (includes country_code and language_code) 
const sourceLanguageArray = _.map(ontomlClass, 'source_language'); 

console.log(sourceLanguageArray); 
// => [ [ { '$': [Object] } ], [ { '$': [Object] } ],[ { '$': [Object] } ] ] 
// => [ { '$': [Object] } ] 

console.log(sourceLanguageArray[0]); 
// => [ { '$': { country_code: 'US', language_code: 'en' } } ] 

回答

1

var sourceLanguageArray = [[ { '$': { country_code: 'US', language_code: 'en' } } ]]; 
 

 
console.log("sourceLanguageArray[0]:", sourceLanguageArray[0]); 
 

 
console.log("country code:", sourceLanguageArray[0][0].$.country_code); 
 
console.log("language code:", sourceLanguageArray[0][0].$.language_code);

+0

謝謝!這解決了它! –

0

試試這個:

sourceLanguageArray.forEach(function(item){ 
    console.log(item[0]['$'][country_code]); 
    console.log(item[0]['$'][language_code]); 
}) 
相關問題