Encounter an error while attempting to store and retrieve an array of JavaScript objects in localStorage and parsing the data

I'm dealing with an array of JavaScript objects, like this:

var objectList = [{phone: true},{name: 'room'}]
.

My goal is to store this array in localStorage, retrieve it later, and continue working with the objects it contains.

Here is what I've attempted:

localStorage.setItem('myObject', JSON.stringify(objectList));
objectsList = JSON.parse(localStorage.getItem('myObject'));

However, I encountered an error message:

Uncaught SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse ()

When I tried

console.log(localStorage.getItem('myObject'))
, the output was:

[object Object],[object Object]

And

console.log(typeof localStorage.getItem('myObject'))
returned string.

How can I properly retrieve and parse the array of objects so that I can work with the objects stored in it?

Thank you!

UPDATE:

var roomsList = [{
category: "ЛЮКС",
cond: true,
wifi: true,
smoke: true,
restrAbility: true,
veranda: true,
kingSizeBed: true,
numFree: 5,
numBusy: 2,
price: 1000,
image: "img/rooms/room0.jpg",
description: "Просторные двухкомнатные люксы с гостиными и уютными спальнями. В оформлении интерьеров использованы предметы антиквариата музейной ценности: мебель, музыкальные инструменты, торшеры и лампы из Богемского стекла - все это рождает уникальный, неповторимый стиль каждого номера. Мраморные ванные комнаты оборудованы гидромассажными ваннами. Все номера данной категории обращены окнами на живописный ансамбль.",
},
{
category: "СТАНДАРТ",
cond: false,
wifi: true,
smoke: false,
restrAbility: false,
veranda: false,
kingSizeBed: false,
numFree: 10,
numBusy: 8,
price: 120,
image: "img/rooms/room0.jpg",
description: "Просторные двухкомнатные люксы с гостиными и уютными спальнями. В оформлении интерьеров использованы предметы антиквариата музейной ценности: мебель, музыкальные инструменты, торшеры и лампы из Богемского стекла - все это рождает уникальный, неповторимый стиль каждого номера. Мраморные ванные комнаты оборудованы гидромассажными ваннами. Все номера данной категории обращены окнами на живописный ансамбль.",
 }] 

and so on.. (14 objects in the array) All other logic and outputs are the same as I described earlier:

var roomsObject = localStorage.getItem('roomsObject');
if (!roomsObject) {
    localStorage.setItem('roomsObject', JSON.stringify(roomsList));
}
roomsList = JSON.parse(localStorage.getItem('roomsObject'));

Answer №1

It seems that the issue stems from saving the object as a string like [object Object],[object Object], causing the parsing to fail. Make sure to convert the object to JSON format (string) before saving it in order to avoid this problem.

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

Region Covered by Mouse Over Does Not Extend Across Whole Div

On my website, there is an arrow located on the middle right side that, when hovered over with the mouse, reveals a sidebar. Clicking on each icon in the sidebar further extends it to reveal more content. However, the issue I am facing is that the sidebar ...

Generate JSON dynamically using a foreach loop

I am utilizing the jquery flot charts library to visualize my data. Take a look at this example JSFiddle I created demonstrating how the JSON structure required for the chart should be. The data I am working with is sourced from a MySql stored procedure a ...

Design a captivating Profile Picture form using HTML and CSS styling

In my form, I am looking to include a user's Profile picture which should be displayed in either a circular or rectangular shape. Initially, the image area will show a black background or a placeholder image. When the user clicks on this area, they sh ...

Tips on concealing all classes except one through touch swiping

If you have a website with a single large article divided into multiple sections categorized as Title, Book1, Book2, & Book3, and you want to implement a swipe functionality where only one section is displayed at a time, you may encounter some issues. ...

The Material UI Popover is appearing outside the designated boundaries

In my app, I am using the code below to implement a react-dates picker controller inside a popover element. The functionality works well in most scenarios, but there is an issue when the button triggering the popover is located at the bottom of the screen, ...

The issue of Angular curly braces malfunctioning in some simple code examples reversed my

<head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"> </script> </head> <body style="padding: 20px 20pc;"> <div ng-app="app"> ...

Allow the words to seamlessly transition back and forth between columns in a continuous cycle

Currently, I am attempting to showcase a large text in a format similar to a book. Each "page" has designated width and height, with content displayed over two columns: left and right. In this layout, page 1 is on the left, page 2 on the right, page 3 on t ...

Issue with AngularJS ui-router failing to resolve a service call

I am facing an issue while trying to implement the resolve feature in my ui-router state provider. Here is how I have configured it: app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function ($stat ...

When you click, transfer a single item from one array to another and modify the text according to the items in the array

How can I dynamically update a shopping cart feature on my website when a user clicks on the "addtocart" button? I want to create functionality where clicking on the button adds the corresponding product to the cart array, and updates the cart amount displ ...

The ng-model used within an *ngFor loop is not displaying the correct value

I am working with a JSON file in my Angular2 App. The specific JSON object I am referring to is named tempPromotion and I am trying to access the data within ['results'] like this: tempPromotion['response_payload']['ruleset_list ...

Ways to conceal the header and footer on specific React pages

I currently have my header and footer wrapping the content on all pages of my website. However, I am looking to hide the header and footer on specific pages like the customer and admin dashboard. Can anyone suggest the best approach to achieve this? cons ...

Setting the initial scroll position in a ReactNative ListView after the data has been loaded

I need a solution for jumping to specific dates in an events section, with the initial scroll position set to the first future date. To achieve this, I have attempted to store the y positions of each date in the state. renderSectionHeader= (sectionData, ...

The dilemma between installing Electron or installing Electron-Builder: which one

When it comes to installing Electron for an Electron app with React, the method can vary depending on the tutorial. Some tutorials use electron-builder while others do not, but there is little explanation as to why. First: npx create-react-app app cd app ...

Can a for loop be implemented within a mongoose schema method?

Is there a way to modify this for loop so that it runs through the entire array instead of adding one by one? Any suggestions? EndorsedSkillSchema.methods = { async userEndorsedSkill(arr) { for (var i = 0; i < arr.length; i++) { const skil ...

Assign a value to ng-model using JavaScript

Encountering an issue while working with JavaScript in AngularJS. There is a text field identified by id="longitude". <input type="text" data-ng-model="newwarehouse.longtitude" id="longitude"/> The value of this field is being set using JavaScript. ...

Transform any falsy values within a JavaScript object into an empty string

Looking for a solution to transform all undefined, NaN, etc. values in a Javascript object into an empty string for better definition. For example: javascriptObject = convertUndefined(javascriptObject) Seeking something that can achieve this functionalit ...

Implement a jQuery DataTable using JSON data retrieved from a Python script

I am attempting to create an HTML table from JSON data that I have generated after retrieving information from a server. The data appears to be correctly formatted, but I am encountering an error with DataTable that says 'CIK' is an unknown para ...

none of the statements within the JavaScript function are being executed

Here is the code for a function called EVOLVE1: function EVOLVE1() { if(ATP >= evolveCost) { display('Your cell now has the ability to divide.'); display('Each new cell provides more ATP per respiration.'); ATP = ATP ...

Embarking on a journey to master the art of JSON

I'm looking to master the process of extracting data from .json files using the Weather Underground API. I've made some progress, but my current script displays the highs and lows for each day. How can I modify it to only show today's high a ...

What is the best way to merge three MongoDB queries into one consolidated query?

I currently have three different sets of data collections structured as shown below: db={ "category": [ { "_id": "64841d0280a7a74a913b7935", "name": "Cat A", }, { &quo ...