本地存储Javascript中的独立对象 [英] Seperate Objects in local storage Javascript

查看:77
本文介绍了本地存储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);

这篇关于本地存储Javascript中的独立对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆