2017-06-13 150 views
0

我有這樣的對象:離子2,遍歷對象

{"": "Select job type", F: "Full-time", P: "Part-time", C: "Contract", T: "Temporary} 

我希望能夠通過它循環,並得到鍵和值。我打算寫一個函數,看起來像

getJobType(letter){ 
     let jobType = JSON.parse(localStorage.getItem('jobType')) 

     //if my letter matches the key in the object then i want to return the value 

    } 

我曾嘗試:

Object.keys(JSON.parse(jobType)).forEach(key=> { 
    console.log(jobType[key]) ;  
    }); 

jobType.forEach((value, key, index) => { 
    console.log("This is the value", value) 
    console.log("from the key", key) 
}) 

,但它不工作。

回答

0

你缺少「在結束‘臨時’,下面的代碼工作的迭代。您還可以使用過濾器的方法來過濾出的值。

var jobTypes = {"": "Select job type", F: "Full-time", P: "Part-time", C: "Contract", T: "Temporary"}; 

Object.keys(jobTypes).forEach(function(key) { 
    console.log(jobTypes[key]) 
});