删除本地存储中的重复数据
我在从 localStorage
中删除重复数据时遇到困难,该平台在 Cordova-Phone Gap 上使用 JavaScript,如何删除 localStorage 上的重复数据?
例如,按 ID 删除重复项 :
[{ID=1, NAME:"JAMES"},
{ID=1, NAME:"JAMES"},
{ID=2, NAME:"HENRY"},
{ID=3, NAME:"JOHN"},
{ID=3, NAME:"JAMES"}]
期望:
[{ID=1, NAME:"JAMES"},
{ID=2, NAME:"HENRY"},
{ID=3, NAME:"JOHN"}]
I am facing difficulty in deleting duplicate data from localStorage
, the platform use JavaScript on Cordova-Phone Gap, how can I delete duplicate data on localStorage ?
For example remove duplicate by ID :
[{ID=1, NAME:"JAMES"},
{ID=1, NAME:"JAMES"},
{ID=2, NAME:"HENRY"},
{ID=3, NAME:"JOHN"},
{ID=3, NAME:"JAMES"}]
Expect :
[{ID=1, NAME:"JAMES"},
{ID=2, NAME:"HENRY"},
{ID=3, NAME:"JOHN"}]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的具体示例中,如果您希望删除具有相同数字
ID
的任何对象,您可以使用 for-each 循环来传输仅当对象尚未发送到共享其ID
的索引时,每个元素中存储的对象才会存储到空数组的元素索引就您而言,由于您没有
ID:0
,因此第一个无重复数组的元素将是未定义的(并且应该通过filter
ing删除)。这是一个工作示例(我在对象中将
=
替换为:
)。这将仅保留每个 ID 的第一个对象如果您想要最后一个而不是给定 ID 的第一个对象,只需从
forEach
循环中删除if (!nonDuplicatedData[x.ID])
即可继续替换对象,留下该 ID 号的最终出现。显然,必须检索您的
localStorage
版本,将JSON.parse
转换为对象并分配给变量(此处为data
)。过滤后,您必须对其进行JSON.stringify
,然后再将其放回localStorage
。另外,这需要数字 ID,这不是通用的解决方案。In your specific example, where you wish to remove any objects with the same numerical
ID
, you can use a for-each loop to transfer the object stored in each element to the element index of an empty array only if an object has not already been sent to the index that shares itsID
in your case, since you have no
ID:0
, the first element of the no-duplicate array will be undefined (and should be removed byfilter
ing).Here is a working example (I replaced
=
with:
in your objects). This will keep only the first object of each IDIf, instead of the first object for a given ID you want the last, simply remove
if (!nonDuplicatedData[x.ID])
from theforEach
loop to keep replacing the object, leaving the final occurence for that ID number.Obviously, your
localStorage
version will have to be retrieved,JSON.parse
d into an object and assigned to a variable (data
here). After filtering, you'd have toJSON.stringify
it before putting it back tolocalStorage
. Also, this requires numeric IDs, it is not a general solution.