我有一个存储为 JSON 数组的 localStorage key (f7Contacts),应该是这样。我知道如何使用 localStorage.removeItem("myKey");
删除整个 key .
如您所见,我的数组是由一组嵌入其中的 JSON 数组组成的。有一个更广泛的名为 f7联系人在其中有一些名为 的子数组(以某种方式命名)访问和 咨询 .现在,我要删除的不是任何 JSON 数组中的单个项目,也不是整个 f7联系人数组,但名为 的 JSON 子数组咨询 .
我尝试了很多方法,但我无法获得有效的代码。
这是我到目前为止所拥有的:
我的 stringify 数组如下所示:
(现在我更新了字符串以使其更像我的真实案例,因为建议的答案设法删除了其中一个联系人中的 consultas
,如果它从第一个联系人中删除 consultas
并删除其余的联系人。我为您命名 ELISA 和 FRANK 以区分它们。还更新了我的 Javascript 和 html 作为我自己的代码和ЖнецЪ的答案之一的混合物。我这样做是为了保持我的环境一致。这段代码设法删除第一个 联系人 的 咨询,同时删除 联系人 的其余部分。):
JAVASCRIPT
document.addEventListener("DOMContentLoaded", function() {
var contacts = [{
id: "95470e9e-ee5c-4467-9500-1fcbeae1b57c",
hasPic: true,
picId: 3,
createdOn: "2021-08-01T17:31:32.230Z",
firstName: "ELISA",
company: "La Fábrica",
job: "Barrendero",
mobile: "+53555555",
phone: "+5372222222",
sms: "",
email: "fulano@nauta.cu",
madedate: "Invalid date",
clinic: "2",
gender: "M",
birthday: "Invalid date",
age: "47",
visitings: [{
id: "1",
vdate: "19/07/-2006 12:00 AM",
pdcb: "Est officia dolorem ",
vdiagnose: "Laborum Ea consecte",
vrecom: "Mollit cillum sed pe",
nextv: "Invalid date"
}],
consultas: [{
id: "1",
ldate: "04/07/-1978 12:00 AM",
lmotive: "Soluta cumque aspern",
ldiagnose: "Quidem autem do ut o",
ttest: "Rerum sint atque il",
etest: "Officiis deserunt un",
mtest: "Nihil a dolore rem s",
nextv: "Invalid date"
},
{
id: "2",
ldate: "04/04/-1991 12:00 AM",
lmotive: "Eius in est enim no",
ldiagnose: "In aliqua Sunt dol",
ttest: "Sunt dolor eu sed N",
etest: "Quia aut reprehender",
mtest: "Unde libero autem an",
nextv: "Invalid date"
}
],
isFavorite: true
},
{id: "95470e9e-ee5c-4467-9500-1fcbeae1b57c",
hasPic: true,
picId: 3,
createdOn: "2021-08-01T17:31:32.230Z",
firstName: "FRANK",
company: "La Fábrica",
job: "Barrendero",
mobile: "+53555555",
phone: "+5372222222",
sms: "",
email: "fulano@nauta.cu",
madedate: "Invalid date",
clinic: "2",
gender: "M",
birthday: "Invalid date",
age: "47",
visitings: [{
id: "1",
vdate: "19/07/-2006 12:00 AM",
pdcb: "Est officia dolorem ",
vdiagnose: "Laborum Ea consecte",
vrecom: "Mollit cillum sed pe",
nextv: "Invalid date"
}],
consultas: [{
id: "1",
ldate: "04/07/-1978 12:00 AM",
lmotive: "Soluta cumque aspern",
ldiagnose: "Quidem autem do ut o",
ttest: "Rerum sint atque il",
etest: "Officiis deserunt un",
mtest: "Nihil a dolore rem s",
nextv: "Invalid date"
},
{
id: "2",
ldate: "04/04/-1991 12:00 AM",
lmotive: "Eius in est enim no",
ldiagnose: "In aliqua Sunt dol",
ttest: "Sunt dolor eu sed N",
etest: "Quia aut reprehender",
mtest: "Unde libero autem an",
nextv: "Invalid date"
}
],
isFavorite: true
}];
// Get from lS
const lS = JSON.parse(localStorage.getItem('f7Contacts'));
// DOM elements
const cancelBtn = document.getElementById('dntdelete');
const deleteBtn = document.getElementById('delete');
const consultas = document.getElementById('consultas');
const json = document.getElementById('json');
function clearConsults(){
document.getElementById('confirm').style.display="block";
{
function removeItem() {
const lS = JSON.parse(localStorage.getItem('f7Contacts'));
if (!lS) return;
const obj = lS[0];
// Find 'consultas' key in the object
const findKey = Object.keys(obj).find(key => key.includes('consultas'));
if (findKey) {
// Delete key from the object with array
delete obj[findKey];
}
// Back wraping the obj into array & put to the localStorage
localStorage.setItem('f7Contacts', JSON.stringify([obj])); //set item back into storage
}
alert('CONSULTAS ELIMINADAS');
document.getElementById('confirm').style.display="none";
if (lS[0].consultas) {
consultas.textContent = lS[0].consultas.length;
}
consultas.textContent = 0;
json.textContent = JSON.stringify(obj, undefined, 2);
}
cancelBtn.addEventListener('click', dntdelete);
deleteBtn.addEventListener('click', clearConsults);
}
});
document.getElementById('dntdelete').onclick = function(){
alert('OPERACIÓN CANCELADA');
document.getElementById('confirm').style.display="none";
return false;
};
HTML <main>
<div class="results">
<h4>Consultas<span id="consultas"></span></h4>
</div>
<div class="control-buttons">
<div id="confirm" style="display: none">
<button id="delete">Delete</button>
<button id="dntdelete">Cancel</button>
</div>
<a onclick="clearConsults()">Delete Consultas</a><h3>SURE YOU WANT TO DELETE?</h3>
</div>
</main>
我必须说清楚这个 本地存储 key (f7Contacts) 确实由应用程序中的另一个 js 存储,如果我包含了 localStorage.setItem("f7Contacts", JSON.stringify(contacts)); 在我上面的代码的开头只是为了让你清楚。还要清楚字符串中有几个联系人,任务是删除consultas
。为他们所有人。
最佳答案
如果我理解正确,您只想删除 consultas
来自 localStorage
.我认为最好用 Object.keys
找到对象的键。然后从对象中删除该键。 working example
脚本.js
document.addEventListener('DOMContentLoaded', function () {
var contacts = [
{
id: '95470e9e-ee5c-4467-9500-1fcbeae1b57c',
hasPic: true,
picId: 3,
createdOn: '2021-08-01T17:31:32.230Z',
firstName: 'ELISA',
company: 'La Fábrica',
job: 'Barrendero',
mobile: '+53555555',
phone: '+5372222222',
sms: '',
email: 'fulano@nauta.cu',
madedate: 'Invalid date',
clinic: '2',
gender: 'M',
birthday: 'Invalid date',
age: '47',
visitings: [
{
id: '1',
vdate: '19/07/-2006 12:00 AM',
pdcb: 'Est officia dolorem ',
vdiagnose: 'Laborum Ea consecte',
vrecom: 'Mollit cillum sed pe',
nextv: 'Invalid date',
},
],
consultas: [
{
id: '1',
ldate: '04/07/-1978 12:00 AM',
lmotive: 'Soluta cumque aspern',
ldiagnose: 'Quidem autem do ut o',
ttest: 'Rerum sint atque il',
etest: 'Officiis deserunt un',
mtest: 'Nihil a dolore rem s',
nextv: 'Invalid date',
},
{
id: '2',
ldate: '04/04/-1991 12:00 AM',
lmotive: 'Eius in est enim no',
ldiagnose: 'In aliqua Sunt dol',
ttest: 'Sunt dolor eu sed N',
etest: 'Quia aut reprehender',
mtest: 'Unde libero autem an',
nextv: 'Invalid date',
},
],
isFavorite: true,
},
{
id: '95470e9e-ee5c-4467-9500-1fcbeae1b57c',
hasPic: true,
picId: 3,
createdOn: '2021-08-01T17:31:32.230Z',
firstName: 'FRANK',
company: 'La Fábrica',
job: 'Barrendero',
mobile: '+53555555',
phone: '+5372222222',
sms: '',
email: 'fulano@nauta.cu',
madedate: 'Invalid date',
clinic: '2',
gender: 'M',
birthday: 'Invalid date',
age: '47',
visitings: [
{
id: '1',
vdate: '19/07/-2006 12:00 AM',
pdcb: 'Est officia dolorem ',
vdiagnose: 'Laborum Ea consecte',
vrecom: 'Mollit cillum sed pe',
nextv: 'Invalid date',
},
],
consultas: [
{
id: '1',
ldate: '04/07/-1978 12:00 AM',
lmotive: 'Soluta cumque aspern',
ldiagnose: 'Quidem autem do ut o',
ttest: 'Rerum sint atque il',
etest: 'Officiis deserunt un',
mtest: 'Nihil a dolore rem s',
nextv: 'Invalid date',
},
{
id: '2',
ldate: '04/04/-1991 12:00 AM',
lmotive: 'Eius in est enim no',
ldiagnose: 'In aliqua Sunt dol',
ttest: 'Sunt dolor eu sed N',
etest: 'Quia aut reprehender',
mtest: 'Unde libero autem an',
nextv: 'Invalid date',
},
],
isFavorite: true,
},
];
// Get from lS
const lS = JSON.parse(localStorage.getItem('f7Contacts'));
// DOM elements
const clearConsultsBtn = document.getElementById('clear-consults');
const confirmBtn = document.getElementById('confirm');
const createBtn = document.getElementById('create');
const cancelBtn = document.getElementById('dntdelete');
const deleteBtn = document.getElementById('delete');
const consultas = document.getElementById('consultas');
const controlBtns = document.querySelector('.control-buttons');
const json = document.getElementById('json');
// Check if not lS
if (!lS) {
localStorage.setItem('f7Contacts', JSON.stringify(contacts));
/// JUST FOR VISIBILITY
let num = 0;
for (const i of contacts) {
num += i.consultas.length;
consultas.textContent = num;
}
json.textContent = JSON.stringify(contacts, undefined, 2);
}
if (lS) {
for (const i of lS) {
if (!i.consultas) consultas.textContent = 0;
}
json.textContent = JSON.stringify(lS, undefined, 2);
}
function removeItem() {
const lS = JSON.parse(localStorage.getItem('f7Contacts'));
if (!lS) return;
// Creating new array without 'consultas'
const clearArray = lS.map(obj => {
// Find 'consultas' key in the object
const findKey = Object.keys(obj).find(key => key.includes('consultas'));
if (findKey) {
// Delete key from the object with array
delete obj[findKey];
}
return obj; // Returning object to array without 'consultas'
});
// Put to the localStorage
localStorage.setItem('f7Contacts', JSON.stringify(clearArray)); //set item back into storage
alert('CONSULTAS ELIMINADAS');
controlBtns.style.display = 'none';
clearConsultsBtn.style.display = 'block';
/// JUST FOR VISIBILITY
if (clearArray) {
for (const i of clearArray) {
if (!i.consultas) consultas.textContent = 0;
}
}
json.textContent = JSON.stringify(clearArray, undefined, 2);
}
function addItem() {
localStorage.setItem('f7Contacts', JSON.stringify(contacts));
/// JUST FOR VISIBILITY
let num = 0;
for (const i of contacts) {
num += i.consultas.length;
consultas.textContent = num;
}
json.textContent = JSON.stringify(contacts, undefined, 2);
}
function clearConsults() {
alert('OPERACIÓN CANCELADA');
controlBtns.style.display = 'flex';
clearConsultsBtn.style.display = 'none';
}
function cancel() {
alert('OPERACIÓN CANCELADA');
controlBtns.style.display = 'none';
clearConsultsBtn.style.display = 'block';
}
clearConsultsBtn.addEventListener('click', clearConsults);
createBtn.addEventListener('click', addItem);
cancelBtn.addEventListener('click', cancel);
deleteBtn.addEventListener('click', removeItem);
confirmBtn.addEventListener('click', clearConsults);
});
index.html <main>
<div class="results">
<h4>Consultas arrays<span id="consultas"></span></h4>
</div>
<h3>SURE YOU WANT TO DELETE?</h3>
<button id="clear-consults">Delete Consultas</button>
<div class="control-buttons">
<button id="dntdelete">Cancel</button>
<button id="delete">Delete</button>
<button id="create">Create</button>
</div>
<div id="confirm"></div>
<pre id="json"></pre>
</main>
样式.css * {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: serif;
}
body,
html {
padding: 20px;
}
main {
min-width: 100%;
display: grid;
grid-template-rows: repeat(4, max-content);
gap: 10px;
justify-content: center;
color: #4c5f6b;
}
.control-buttons {
display: none;
gap: 20px;
}
button {
padding: 8px 15px;
border: none;
color: #4c5f6b;
border-radius: 3px;
cursor: pointer;
}
#cancel {
background-color: #4c5f6b;
}
#delete {
background-color: #89608e;
color: whitesmoke;
}
#create {
background-color: #6eaa8d;
color: whitesmoke;
}
.results {
display: flex;
gap: 20px;
}
.results h4 {
text-transform: lowercase;
}
.results span {
width: 50px;
margin-left: 5px;
padding: 3px 9px;
border: 2px solid #6eaa8d;
}
#confirm {
display: none;
}
pre {
font-size: 10px;
}
关于javascript - 如何删除嵌入在另一个 JSON 数组 (f7Contacts) 中的特定 JSON 数组 (consultas),这两个数组都保存在单个 localSorage 键中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68612472/