2017-05-08 41 views
0
let listValue = [ 
    { 
     key: '1', 
     value: { 
      mark: 'Audi', 
      model: 'A1', 
     } 
    }, 

    { 
     key: '2', 
     value: { 
      mark: 'Audi', 
      model: 'TT', 
     } 
    } 

]; 

localStorage.setItem('listValue', JSON.stringify(listValue)); 
let carObj = JSON.parse(localStorage.getItem('1')); 
document.getElementById("new2").innerHTML = carObj.mark; 
+1

您正在使用項目與關鍵「設置listValue '並通過鍵'1'獲取? – krrish

回答

0

你必須從localStorage使用相同的名稱「listValue」獲得項目:localStorage.getItem('listValue')

然後,要從排列listValue的字符串key中獲取該車,您可以製作一個Array.prototype.find()

檢查在工作演示:https://jsfiddle.net/yosvelquintero/vanus5ah/1/

代碼:

let listValue = [{ 
    key: '1', 
    value: { 
    mark: 'Audi', 
    model: 'A1', 
    } 
}, { 
    key: '2', 
    value: { 
    mark: 'Audi', 
    model: 'TT', 
    } 
}]; 

localStorage.setItem('listValue', JSON.stringify(listValue)); 

let carObj = JSON.parse(localStorage.getItem('listValue')); 

// Find the car by key '1' 
let car = carObj.find((c) => c.key === '1'); 

document.getElementById('new2').innerHTML = car.value.mark; 
0

改變你的代碼是這樣的:

let listValue = [ 
{ 
    key: '1', 
    value: { 
     mark: 'Audi', 
     model: 'A1', 
    } 
}, 

{ 
    key: '2', 
    value: { 
     mark: 'Audi', 
     model: 'TT', 
    } 
} 

]; 

localStorage.setItem('listValue', JSON.stringify(listValue)); 
var carObj = JSON.parse(localStorage.getItem('listValue')); 

for (var i=0; i<=carObj.length -1; i++){  
    document.getElementById("demo").innerHTML += " " + carObj[i].value.mark; 
} 

https://jsfiddle.net/emilvr/58pq114n/1/