在本地存储Javascript中分离对象

时间:2017-09-07 10:57:01

标签: javascript jquery arrays google-chrome local-storage

我目前在本地存储中有一个项目,如下所示

"cars":[
{
"Id":7,
"Name":"Audi",
},
{
"Id":8,
"Name":"Ford",
}

我想只检索所有Id,并将它们存储在一个字符串中。 在那一刻我将拉出这样的数据:

var cars = "";
cars= localStorage.getItem('cars');
var carArr= new Array();
carArr.push(cars);

我如何才能获得Id

3 个答案:

答案 0 :(得分:2)

如果我正确理解您的问题,您必须使用Array.map将您的数组与JSON.parseJSON.stringify结合使用,以便从存储中读取/写入。

这是一个使用"模拟"的示例。 localStorage的:



// use a mock storage because snippet doesn't allow localStorage usage.
var mockStorage = {};

// setup initial storage
try {
  mockStorage.cars = JSON.stringify([
    {
      Id:7,
      Name:"Audi",
    },
    {
      Id:8,
      Name:"Ford",
    }
  ]);
} catch(e) {}
console.log('inital local storage:\n', mockStorage);


// example

var cars = [];

// parse JSON string value from storage to javascript object.
try {
  cars = JSON.parse(mockStorage.cars)
} catch(e) {}
console.log('cars:\n', cars);
// transform array of cars to array of car ids
var ids = cars.map(car => car.Id)
console.log('car ids:\n', ids);
// transform array to JSON string
try {
  mockStorage.cars = JSON.stringify(ids);
} catch(e) {}
console.log('local storage:\n', mockStorage);




答案 1 :(得分:1)

使用此,

//you get this from localStorage after you parse it
//JSON.parse(localStorage.cars);
var cars = [
{
"Id":7,
"Name":"Audi",
},
{
"Id":8,
"Name":"Ford",
}];
var res = [];
cars.forEach(function(val){
  res.push(val.Id);
});

console.log(res);

答案 2 :(得分:1)

localStorage仅支持strings。因此,您必须使用JSON.parse从字符串中获取cars数组,然后使用array#map来获取所有ID。

var carsString = localStorage.getItem('cars');
var cars = JSON.parse(carsString);

var ids = cars.map( car => car.Id);
console.log(ids);