【发布时间】:2017-11-16 08:02:47
【问题描述】:
我正在尝试将此对象保存到$window.localStorage():
ctrl:
app.controller('ctrl', function($window, $scope) {
$scope.initData = [
{
customer: 1,
firstName: "John",
lastName: "Doe"
},
{
customer: 2,
firstName: "Jane",
lastName: "Doe"
},
{
customerId: 3,
firstName: "John",
lastName: "Smith",
}
];
// scopes
for(var i = 0; i < $scope.initData.length; ++i) {
$window.localStorage.setItem(i, JSON.stringify($scope.initData[i]));
}
});
但是我用键作为索引的值..我也试过这个:
for(var i = 0; i < $scope.initData.length; ++i) {
$window.localStorage.setItem(i, Object.values($scope.initData[i]));
}
和for..in,但不知道什么是最好的方法。
现在,当我执行console.log(localStorage); 时,我将其作为输出:
0:"{"customer":1,"firstName":"John","lastName":"Doe"}"
1:"{"customer":2,"firstName":"Jane","lastName":"Doe"}"
2:"{"customer":3,"firstName":"John","lastName":"Smith"}"
当我访问0 作为键时,我得到customer 作为值,我需要得到1 作为值。 customer 应该是关键。
我怎样才能做到这一点?如何转换?
【问题讨论】:
-
如果你把
customer作为一个键,就会有多个同名的键。而这是做不到的。 -
我知道,这就是我转向数组的原因。我现在如何访问
customer作为关键参考?
标签: javascript jquery html angularjs local-storage