更新本地存储中的对象数组而不保留 null



所以我有 3 个文本输入字段,输入作为对象数组存储在本地存储中。 看起来像这样:

[{name: " Name1", description: "Description1", comment: "Comment1"},…]
0: {name: " Name1", description: "Description1", comment: "Comment1"}
1: {name: " Name2", description: "Description2", comment: "Comment2"}
2: {name: " Name3", description: "Description3", comment: "Comment3"}

我需要能够删除我选择的任何条目并更新本地存储。

在JSON.parse之后,我得到了一个javascript对象,而不是一个数组。 如果我使用 delete[X],它会留下

空值 -
[null, {name: " Name2", description: "Description2", comment: "Comment2"},…]
0: null
1: {name: " Name2", description: "Description2", comment: "Comment2"}
2: {name: " Name3", description: "Description3", comment: "Comment3"} 

有什么办法可以避免这种情况,我需要完全消失条目并更新索引,以便"name2..."将获得索引 0,依此类推。

有什么办法吗? 谢谢!

可以使用筛选器删除数组项null

let newVals = [null, {
name: " Name2",
description: "Description2",
comment: "Comment2"
}, {
name: " Name3",
description: "Description3",
comment: "Comment3"
}].filter(x => x);
console.log(newVals);

与其改变数组,不如过滤掉它: 示例:

const newArr = [...].filter(o => o.name != <name you want to remove>)

您有多种选择可以执行此操作。

选项 1:.splice((

splice(( 方法通过删除或替换现有元素和/或添加新元素来更改数组的内容。

const data = [{name: " Name1", description: "Description1", comment: "Comment1"}, {name: " Name2", description: "Description2", comment: "Comment2"}, {name: " Name3", description: "Description3", comment: "Comment3"}];
const s = data.splice(1,1);
console.log(data, 'removed: =>', s);

选项 2:.filter((

filter(( 方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。

const data = [{name: "Name1", description: "Description1", comment: "Comment1"}, {name: " Name2", description: "Description2", comment: "Comment2"}, {name: " Name3", description: "Description3", comment: "Comment3"}];
console.log(data.filter(item => item && item.name !== 'Name1'))

选项 3:循环

如果要从数组中删除项目,最好使用数组方法

array.splice(index, 1);

如果要从对象中删除项目

delete array[x]
let newArray = array.filter(x => x)

所以新数组没有空值

始终确保获取值,更新数组并再次设置。希望这有帮助。

const data = [
{ name: " Name1", description: "Description1", comment: "Comment1" },
{ name: " Name2", description: "Description2", comment: "Comment2" },
{ name: " Name3", description: "Description3", comment: "Comment3" }
];
const setLS = arr => localStorage.setItem("my_data", JSON.stringify(arr));
const getLS = () => JSON.parse(localStorage.getItem("my_data"));
const removeItemLS = obj => {
const current = getLS();
setLS(current.filter(item => item.name !== obj.name));
};
setLS(data);
getLS();
// (3) [{…}, {…}, {…}]
removeItemLS({ name: " Name2" });
getLS();
// (2) [{…},{…}]

最新更新