I have a localStorage key (f7Contacts) stored as a JSON array, as it should be. I know how to delete the whole key using localStorage.removeItem("myKey");
.
My array, as you can see is formed by a set of JSON arrays embeeded inside of it. There is the wider one named f7Contacts and inside of it there are some subarrays (to name them someway) named visitings and consultas. Now, what I'm trying to delete is not a single item from any of the JSON arrays nor the whole f7Contacts array but the JSON sub array named consultas.
I have tried so many ways but I could not get a working code.
This is what I've got until now:
My stringify array looks like this:
(now I have up dated the string to make it more alike my real case because the proposed answers manage to delete the consultas
just in one of the contacts, and in a case it deletes the consultas
from the first contact and deletes the rest of the contacts. I named ELISA and FRANK for you to differetiate them. Also updated my Javascript and html as a mixture from my own code and the one of ЖнецЪ's answer. I did this to keep my enviroment consistent. This code manage to delete the consultas of the first contact but also deletes the rest of the contacts.):
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: "[email protected]",
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: "[email protected]",
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>
I must let it clear that this localStorage key (f7Contacts) is really stored by another js within the app and if I have included the localStorage.setItem("f7Contacts", JSON.stringify(contacts)); at the beginning of my code above is just as an attempt to make it clear for you. And let clear too that there are several contacts within the string and the task is to delete consultas
for them all.
If i'm right understood you want removed only consultas
from the localStorage
. I think better to find the key of the object with Object.keys
and then delete that key from the object. working example
script.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: '[email protected]',
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: '[email protected]',
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>
style.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;
}
when you read a particular item from localStorage
it returns a string, and there is no way to remove some particular item from the saved data, but you can convert the saved data to a Object
and then use delete
operator to delete anything from that object
// This is Sample Data for demonstration purposes
// And from this sample data i want to remove this Gender item
const data = {
name: "Andrew",
email: "[email protected]",
gender: "male"
}
// Here you set your Data by Converting it into a String using JSON.stringify()
localStorage.setItem('data', JSON.stringify(data))
console.log(localStorage.getItem('data'))
// Prints out {"name":"Andrew","email":"[email protected]","gender":"male"}
let storedData = localStorage.getItem('data') // Get Data from localStorage
let newData = JSON.parse(storedData) // Convert it back into a object using JSON.parse()
delete newData.gender // Then remove a item using delete operator
localStorage.setItem('data', JSON.stringify(newData)) // Saving to LocalStorafe
console.log(JSON.parse(localStorage.getItem('data')))
// Prints Out {name: "Andrew", email: "[email protected]"}
Read More About Delete
Operator at MDN Documentations
Edit to remove the item you wanted try this out:
var contacts = { f7Contacts: [{
"id": "95470e9e-ee5c-4467-9500-1fcbeae1b57c",
"hasPic": true,
"picId": 3,
"createdOn": "2021-08-01T17:31:32.230Z",
"firstName": "Fulano Menganejo Ciclanejo",
"company": "La Fábrica",
"job": "Barrendero",
"mobile": "+53555555",
"phone": "+5372222222",
"sms": "",
"email": "[email protected]",
"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
}]
};
console.log(contacts.f7Contacts[0].hasOwnProperty("consultas"));
// Prints true
delete contacts.f7Contacts[0].consultas
console.log(contacts.f7Contacts[0].hasOwnProperty("consultas"));
// Prints False
So i already told you what delete
operator does, now just by using delete see how you can delete a item!
Explaination: well Object.hasOwnProperty(property)
simple returns true
if that given object has a property, in our example it's consultas and it returns false
if that object has no property like that!
Read About Object.hasOwnProperty(property)
at MDN Docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With