一段时间以来,我一直在尝试从有点复杂的JavaScript对象中删除特定数据。
我尝试了很多方法,但最后,我的数据没有被删除,但有时又返回已删除的数据。
这是我的对象:
const lists = [{
client1 : {
userid: "1234",
isLoading: false,
isAuthenticated: true,
devices: [
{id: "67", title: "my title", price: "$38", arrived: "today"}, {id: "68", title: "my title", price: "$88", arrived: "yesrerday"}, { id: "69", title: "my title", price: "$98", arrived: "today" }]
},
client2 : {
id: "1834",
isLoading: false,
isAuthenticated: true,
devices: [
{id: "87", title: "my title", price: "$18", arrived: "today"}, {id: "48", title: "my title", price: "$18", arrived: "yesrerday"}, { id: "39", title: "my title", price: "$58", arrived: "yesterday" }]
}
}]
该对象已经使用localStorage保存在内存中。现在单击这些设备之一,我们应该只能删除该特定设备。
我正在使用ReactJS,Redux并使用ES6的功能。到目前为止,这是我尝试过的:
const applyDelete = (state, payload) {const devices = JSON.parse(localStorage.getItem("lists"))["0"][localStorage.getItem("user")].devices;
const remaining = devices.filter(device => divice.id !== payload);
const newList = [{
[localStorage.getItem("user")]: { id: payload, devices: [...remaining], usLoading: false, isAuthenticated: true }
}];
return newList;
};
payload是通过操作创建者发送的产品的ID。
我尝试了其他解决方案,但结果是相同的。我面临的最大问题是,删除产品后,所有列表都会随之删除。但是并没有真正删除,因为当您刷新时,它们仍然会全部恢复。
因此,请您从此对象删除此类特定数据并将其保存回localStorage的任何见识。
先谢谢您。
根据我的理解,这是您想要的:与有效负载值匹配的设备ID应该从设备数组中过滤掉,并且更新后的列表必须存储在localStorage中。像下面的列表对象中一样,对于用户'client2',您希望过滤设备ID 87,这在下面的代码中进行了演示,并在localstorage中进行了更新。
const lists = [{
client1 : {
userid: "1234",
isLoading: false,
isAuthenticated: true,
devices: [
{id: "67", title: "my title", price: "$38", arrived: "today"}, {id: "68", title: "my title", price: "$88", arrived: "yesrerday"}, { id: "69", title: "my title", price: "$98", arrived: "today" }]
},
client2 : {
id: "1834",
isLoading: false,
isAuthenticated: true,
devices: [
{id: "87", title: "my title", price: "$18", arrived: "today"}, {id: "48", title: "my title", price: "$18", arrived: "yesrerday"}, { id: "39", title: "my title", price: "$58", arrived: "yesterday" }]
}
}];
localStorage.setItem('lists', JSON.stringify(lists));
let tempList=JSON.parse(localStorage.getItem('lists'));
const remaining = tempList[0]['client2']['devices'].filter(device => device.id !== "87");
tempList[0]['client2']['devices'] = remaining;
localStorage.setItem('lists',JSON.stringify(tempList));
console.log(JSON.parse(localStorage.getItem('lists')));
目前,我已经为id和user分配了静态值。通过使用这种方法,可以将列表的值设置为一个新对象,该对象具有较旧的值加上更新的值。最后更新localStorage的“列表”值。在刷新页面时,更新后的值仍然保留。
据我说,您返回的数组仅包含更新的对象,而不是旧数组中的其他条目,因此未提供正确的输出。
希望这是您想要的。