Get a specific value from a JSON object

Within my Calendar, there is a code snippet that includes an Object and JSON data. This JSON object contains various properties such as

   [{"Date":"17-3-2015","Event":"Test drive","Participants":"John, George","Description":"Testing a new F30"},
    {"Date":"17-3-2015","Event":"Football match","Participants":"FCSM vs FCKK","Description":"New season start"},
    {"Date":"25-3-2015","Event":"Jane's Birthday","Participants":"Jane, John, Richard, Alice","Description":"Celebration with my friends"}]

The data is stored in localStorage, so I retrieved it using this code:

var existEvents = JSON.parse(localStorage.getItem('events'));
for(i=0; i<existEvents.length; i++) {
    var item = localStorage.getItem(localStorage.key(i));
    console.log(item);
};

existEvents holds all the new events from my Calendar

console.log(item); displays the data mentioned above.

My goal is to extract every Date value (= key) from the data. I tried using

 item.Date

believing it would work, but unfortunately, it doesn't. I also attempted

item[0].value

I experimented after reviewing this question + answers Access / process (nested) objects, arrays or JSON

What am I missing here? Any assistance is appreciated!

Answer №1

An effective method to utilize the Array.ForEach() function is by employing it to iterate over objects with the value as the primary parameter and the key (if applicable) as the secondary parameter. In the provided example, each iteration of the foreach loop processes one object from the array.

The object being processed contains a key labeled Date, which can be accessed using obj.key. It is advisable to always verify the existence of a key before accessing it by utilizing .hasOwnProperty.

Additionally, you have the option to use forEach to traverse through the keys of the object, enabling access to obj/key. For instance, iterating over each obj within the array will output

obj => 17-3-2015 | key => Date
...etc.

var x =  [{"Date":"17-3-2015","Event":"Test drive","Participants":"John, George","Description":"Testing a new F30"},
        {"Date":"17-3-2015","Event":"Football match","Participants":"FCSM vs FCKK","Description":"New season start"},
        {"Date":"25-3-2015","Event":"Jane's Birthday","Participants":"Jane, John, Richard, Alice","Description":"Celebration with my friends"}];

x.forEach(function(obj,key){console.log(obj.Date) });

Here is an example of how your code could look:

JSON.parse(localStorage.getItem('events')).forEach(function(obj,key){console.log(obj.Date) });

Answer №2

Avoid accessing localstorage multiple times within a loop when you have already stored all the necessary data in the 'existEvents' variable.

var existEvents = JSON.parse(localStorage.getItem('events'));
for(i=0; i<existEvents.length; i++) {
    var item = existEvents[i];
    console.log(item);
};

Answer №3

When it comes to HTML5 LocalStorage, it serves as a key-value storage system where the getItem function allows you to retrieve specific items. For example,

localStorage.getItem("somekey")

will return the value associated with the key somekey. In the code snippet provided, the data stored in the localStorage is a String formatted in JSON notation. By using JSON.parse(), you can convert this JSON string back into an array.

var existEvents = JSON.parse(localStorage.getItem('events'));
for (var i = 0; i < existEvents.length; i++) {
    var item = existEvents[i];
    console.log(item);
};

Since existEvents now contains an Array object, you can interact with it like any regular array. Once you have retrieved and parsed it from localStorage, there's no need to keep accessing localStorage.getItem.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Managing JavaScript expiration time in API responses

Seeking help with a JavaScript API I'm new to. The response I received contains a timestamp, which seems like it's in milliseconds. I want to format this time for a countdown but I'm not sure what these milliseconds are referring to. I know ...

Injecting Ajax-loaded content into an HTML modal

Hey there! I'm currently working on a project involving the IMDb API. The idea is that when you click on a film title, a popup should appear with some details about the movie. I've made some progress, but I'm stuck on how to transfer the mov ...

Problem encountered when attempting to return data received from database queries executed within a loop

Having an issue with making multiple MongoDB queries in a loop and trying to send all the results as one data array. However, simply using 'return' to send the data is resulting in 'undefined' and not waiting for the results of all DB r ...

Ways to alter the div post user authentication

I'm in the process of developing a website with a single-page application setup. I'm utilizing Node.js for the backend and Angular for the frontend. The challenge I'm facing is displaying a specific div when a user is not logged in, and swit ...

Implementing SVG in NextJS 13 with custom app directory: A step-by-step guide

Recently, I decided to explore the app directory and unfortunately ran into some issues. One of the main problems I encountered was with image imports. While PNG images imported without any problem, SVG images seemed to break when importing in /app. For i ...

How to transfer the application version from package.json to a different non-JSON file in Angular and node.js

While developing my Angular application, I encountered a task where I needed to extract the version number from the package.json file and transfer it to a non-json file. The content of my package.json file is as follows: { "name": "my app ...

Adding a collection of items to an array in preparation for organizing

Realizing that sorting objects is not feasible - despite the necessity of having the object values sorted - I conclude that the only option is to move the object array content into a new array for sorting purposes. The following code generates the output ...

APNS functionality is supported by APN providers, but it is not compatible with NodeJS in a production

I've set up a nodeJS script to send APNs. In development, it always works flawlessly. However, when I switch to production, the notifications never go through. Oddly enough, when I use the same notification ID with my production certificate in Easy Ap ...

How can I override the default success_url and redirect to a custom page in Stripe Checkout?

QUESTION: I have been experiencing an issue with a webhook in my Node.js application. When the event 'checkout.session.completed' is triggered, the user is automatically redirected to the success_url, regardless of my attempts to redirect them t ...

What factors determine when Angular automatically triggers a setTimeout function compared to another?

Sorry if this all seems a bit odd, but I'll do my best to explain the situation. We have been given access to a small service that provides a simple form UI which we collect results from using an event. We've successfully implemented this in two ...

Using react hooks, I am refreshing the product image by replacing it with the thumbnail image

I'm currently working on an e-commerce platform that resembles Amazon. In the product detail page, I want the right side image to update when I click on a thumbnail image on the left side. The issue I'm facing is that upon first loading, the def ...

Retrieve the jsonb value from a json structure that includes a json array in PostgreSQL

I am working with a JSON column that contains data like the following: {"image_pose_array": [{"image_name": "0026568143_WS.jpg", "image_pose": "EXTRA", "is_blurred": false, "is_dark": fal ...

Exploring the World of Background Processes in Meteor

Is there a way to incorporate background tasks, possibly using a workers pool? I'm interested in exploring this concept further and potentially developing a package for it. Can you point me in the right direction? ...

"Looking for a way to create a new line in my particular situation. Any tips

Here is the code snippet I am working with: let list: Array<string> =[]; page.on('request', request => list.push('>>', request.method(), request.url()+'\\n')); page.on('respon ...

dismiss facial recognition event

Does anyone know how to implement a cancel button in Facebox when using it to delete data from MySQL? I want the window to unload when the user clicks on cancel. This is the code snippet I am currently using with Facebox: Are You Sure You Want To Delete ...

What might be the reason for the misaligned positioning of the ThreeJS canvas when the browser window is resized?

My goal is to perfectly align a ThreeJS canvas (with a blue background and yellow text) within the transparent cut-out of the green image. So far, everything is working fine, but I've noticed that resizing the browser window or zooming causes the canv ...

When incorporating <Suspense> in Next.js, the button's interaction was unexpectedly lost

'use client' import React, { Suspense } from "react"; const AsyncComponent = async () => { const data = await new Promise((r) => { setTimeout(() => { r('Detail'); }, 3000) }) as string; return <div>{d ...

Converting Cookies to Numeric Values in JavaScript: A Step-by-Step Guide

I'm currently developing a cookie clicker website and am encountering an issue with saving the user's score to localstorage when they click the "save" button. Here is what my code looks like: let score = 0; function addPoint() { score += 1; } ...

Increasing the top padding of a resized iframe thanks to iframe-resizer

Currently, I am utilizing the remarkable iframe-resizer library to resize an iFrame while keeping it in focus. The challenge I am facing is my inability to figure out how to include additional padding at the top of the iFrame once it's resized. The ...

What steps do I need to follow in order to set up webpack.config.js to convert my HTML file to JS in a Reactjs application

My current folder structure is shown below: https://i.sstatic.net/mSdcH.png Upon attempting to run my React app, I encountered the following error: Failed to compile. ./src/css/owl.html 1:0 Module parse failed: Unexpected token (1:0) To resolve this is ...