I stored some object in localStorage, how i can access all of data using loop.I want to work with long data. How can i find the
solution.
** I have some data in object like as: **
From Local storage:
Basic:{
Question:{
Question1:{
Id:1,
Question: "what is php?",
},
Question2:{
Id:1,
Question: "what is js?",
},
},
}′
Medium:{
Question:{
Question1:{
Id:1,
Question: "what is php?",
},
Question2:{
Id:1,
Question: "what is js?",
},
},
}
Advanced:{
Question:{
Question1:{
Id:1,
Question: "what is php?",
},
Question2:{
Id:1,
Question: "what is js?",
},
},
}
Html:
<div class="process"> <li> Basic </li> <li> Medium </li> <li> Advanced </li>
I tried to access like:
Object obj = new Object(); $('.process li').each(function (){ obj = JSON.parse(localStorage[$(this).text()]; obj[$(this).text()]['question'].each(function(){
How can i print all id & question
}); });
I tried lots of way. But don't get any best solution. Please help me to solve this issue.
Thanks :-)
You would be better off restructuring your data so that it's an object with basic/medium properties that are arrays of objects. Iterating over those array is then pretty simple.
Here's a jQuery example.
const data = {
basic: [{
id: 1,
question: 'what is php?'
},
{
id: 2,
question: "what is js?"
}
],
medium: [{
id: 3,
question: 'what is narwhal?'
},
{
id: 4,
question: "what is goat?"
}
]
};
const list = $('ul');
const keys = Object.keys(data);
for (const key of keys) {
const type = $(`<li>${key}</li>`);
const sublist = $('<ul></ul>');
for (const q of data[key]) {
const item = `<li>${q.id}: ${q.question}</li>`;
sublist.append(item);
type.append(sublist);
}
list.append(type);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul></ul>
The native JS is very similar.
const data={basic:[{id:1,question:"what is php?"},{id:2,question:"what is js?"}],medium:[{id:3,question:"what is narwhal?"},{id:4,question:"what is goat?"}]};
const list = document.querySelector('ul');
const keys = Object.keys(data);
for (const key of keys) {
const type = document.createElement('li');
const sublist = document.createElement('ul');
type.textContent = key;
for (const q of data[key]) {
const item = document.createElement('li');
item.textContent = `${q.id}: ${q.question}`;
sublist.appendChild(item);
type.appendChild(sublist);
}
list.appendChild(type);
}
<ul></ul>