将数组对象推入本地存储 [英] push array object into localstorage

查看:292
本文介绍了将数组对象推入本地存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var arr = [];
var obj = {};

obj.order_id = 1;
obj.name = "Cake";
obj.price = "1 Dollar";
obj.qty = 1;

arr.push(obj);

localStorage.setItem('buy',JSON.stringify(arr));

上述代码的问题是执行时它将替换现有的数组对象,如果order_id不相同,如何将新的obj添加到数组中?

The problem with above code is when executing it will replace the existing array object, how to add new obj into the array if the order_id is not the same?

推荐答案

新答案:

var arr = [];
var obj = {};

obj.order_id = 1;
obj.name = "Cake";
obj.price = "1 Dollar";
obj.qty = 1;

$change = 'no'; for(i=0; i<arr.length; i++){ if(obj.order_id == arr[i].order_id){ obj.qty = obj.qty + arr[i].qty; arr[i] = obj; $change ='yes'; } }
if($change == 'no'){ arr.push(obj); }

console.log(arr);

要将其保存在本地存储中,请在此处查看我的答案:推送多个数组对象放入本地主机?

And for saving it in localstorage see my answer here: push multiple array object into localhost?

旧答案: 最好的解决方案是使"arr"成为一个对象,而order_id是该对象的键.你会得到这样的东西:

Old Answer: The best solution would be to make 'arr' an object with the order_id being the key of the object. You get something like this:

var arr = {};
var obj = {};

obj.order_id = 1;
obj.name = "Cake";
obj.price = "1 Dollar";
obj.qty = 1;

arr[obj.order_id]= obj;
console.log(arr);

仅在order_id相同时,它将替换订单.如果您确实需要数组,则必须创建一个遍历数组并检查每个order_id的函数.

This will only replace the order if the order_id is the same. If you really want and array, you have to make a function that goes through the array and checks every order_id.

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

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