本地存储Javascript中的独立对象

本地存储Javascript中的独立对象

问题描述:

我目前在本地存储中有一个看起来像这样的项目

I currently have an item in local storage which looks like this

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

我只想检索所有Id并将其存储在字符串中. 在此刻,我正在像这样提取数据:

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);

我如何才能获得ID

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

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);