[英]How can I convert an array of objects into JSON (and return it)?
For simplicity's sake, I have a JavaScript Array of car
objects as below (one example): 为了简单起见,我有一个JavaScript的car
对象数组,如下所示(一个示例):
var car = {
"color": "red",
"fuelType": "diesel"
}
I'd like to store this array of objects in the user's localStorage and be able to retrieve and add/delete to it. 我想将此对象数组存储在用户的localStorage中,并能够对其进行检索和添加/删除。
Here is some example code that I cannot seem to get right. 这是一些我似乎无法理解的示例代码。
addCar(car);
function getCars() {
var cars = [];
if (localStorage['cars']) {
cars = localStorage['cars'];
}
return cars;
}
function addCar(car) {
var cars = getCars();
cars.push(car);
localStorage['cars'] = cars;
}
How can I convert an array of objects into JSON (and return it)? 如何将对象数组转换为JSON(并返回)? localStorage
only allows for the storage of Strings. localStorage
仅允许存储字符串。 I need to convert the array of objects into a JSON format, but I am not sure how. 我需要将对象数组转换为JSON格式,但不确定如何。
据我所知,本地存储仅支持字符串,因此您必须使用JSON.stringify()
和JSON.parse()
来获取和获取数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.