问题
I currently have an item in local storage which looks like this
"cars":[
{
"Id":7,
"Name":"Audi",
},
{
"Id":8,
"Name":"Ford",
}
I want to retrieve all of the Id's only and store them in a string. At the minute I am pulling the data like this:
var cars = "";
cars= localStorage.getItem('cars');
var carArr= new Array();
carArr.push(cars);
How can I just obtain the Id's
回答1:
localStorage only supports strings. So, you have to use JSON.parse to get the cars array from string and then use array#map to get all the ids.
var carsString = localStorage.getItem('cars');
var cars = JSON.parse(carsString);
var ids = cars.map( car => car.Id);
console.log(ids);
回答2:
If i understand your question correctly, you have to use Array.map to transform your array in combination with JSON.parse and JSON.stringify to read/write from the storage.
Here is an example using a "mocked" 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);
回答3:
Use this,
//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);
来源:https://stackoverflow.com/questions/46094597/seperate-objects-in-local-storage-javascript