Extend an array by Parsing JSON

I'm struggling to retrieve the JSON string from localStorage and add a new dish to it. It's not functioning correctly, can anyone lend me a hand? I am utilizing TypeScript.

interface Dish { 
    id: number;
    name: string;
    desc: string;
    price: number;   
};

export class BasketService {
    private BASKET: string = 'basket';

    log(dish: Dish) {

        var dishList: Dish[] = [];

        if (!localStorage.getItem(this.BASKET)) {
            dishList.push(dish);    //push the first dish (if local storage is empty)
        }

        //Append an injected dish to the existing local storage.
        dishList.push(JSON.parse(localStorage.getItem(this.BASKET)));
        dishList.push(dish);

        localStorage.setItem(this.BASKET, JSON.stringify(dishList));
    }
}

Expected outcome: The dish should be successfully appended and stored in localStorage for future use.

Answer №1

When working with arrays in javascript, it is important to understand the correct way to concatenate them. Using array1.push(array2) will push array as an object (1 item) into array1.

var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
array1.push(array2);//[1, 2, 3, [4, 5, 6]]

Instead of using push, a better approach is to use Array.prototype.concat. This method allows you to concatenate arrays without modifying the original array.

In order to avoid adding the same element twice when dealing with empty localStorage, consider the following updated code:

var json = localStorage.getItem(this.BASKET);
if (!json) {
    dishList = [dish];
} else {
    dishList = JSON.parse(json);
    dishList.push(dish);
}
localStorage.setItem(this.BASKET, JSON.stringify(dishList));

Answer №2

When we use JSON.parse(localStorage.getItem), the result is typically a JSON object represented as an array.

var dish = [];
var test = JSON.parse(localStorage.getItem("dummy"));
// test = {a : ['aa','bb','cc']}
dish = test.a;
dish.push('dd');
test.a = JSON.stringify(dish);
localStorage.setItem("dummy", test);

This process should be adhered to carefully.

It appears that directly pushing the object into the Dishlist could be causing issues.

The code snippet provided is in plain JavaScript since I am not very familiar with TypeScript. I hope this explanation clarifies things for you.

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

how to transfer data from backend servlet to frontend javascript

Hey, I'm still learning about servlets so please excuse any confusion in my message! So basically, I'm trying to figure out how to pass a value from a servlet to JavaScript or even retrieve values from a servlet method within JavaScript. But I&ap ...

The error message 'tagName' is not a valid property for type ChildNode in Typescript

When I loop over childNodes from a parent node, I encounter an issue while trying to access the tagName of the child nodes. The error message states that tagName does not exist on type ChildNode. const contentParsed = new DOMParser().parseFromString(conte ...

Troubleshooting the lack of deep linking functionality in an AngularJS web application when using Node Express server

(Update: The problem has been successfully solved. Check the end of the question for details) I am currently facing a seemingly trivial issue that is causing me a great deal of frustration as I struggle to find a solution: After scaffolding an Angular ap ...

Choose a random node from Xpath with multiple nodes using JavaScript WebdriverIO

Is there a way to retrieve a random node from an Xpath that contains multiple nodes whose count varies weekly? I am looking for a solution that would work in one of two ways: Return the total number of nodes corresponding to the Xpath, allowing me to the ...

Validating multiple fields that are added dynamically using jQuery

I am facing an issue with form validation using jQuery. The problem is that when one field is valid, the form gets submitted automatically. Here is a link to my code: http://jsfiddle.net/cvL0ymu7/. How can I ensure that all fields are validated before subm ...

What steps should I take to ensure my clock stays in sync with my runTime function?

I am developing a mini digital clock project with the ability to mimic a physical clock. The clock is activated by using a power button to switch it on and display the current time. It should also be able to turn off and show an empty screen. However, th ...

What is the best way to send a function to the child component?

I need help with passing a function to a child component in React. Specifically, I have a component with a modal for confirming the deletion of an item. How can I pass a delete function to the modal so that when the "Agree" button is clicked, it triggers t ...

An Android error message is displaying: "JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject"

My introduction to JSON is quite recent, and I've been watching Youtube videos for guidance on handling the error described in this link: question. Despite my efforts, I'm still confused as to why I keep encountering the same error. Here's ...

Using the datetime picker format will automatically add 5 years to the selected date

When applying the datetime picker, I am using the following code snippet to format the date: $('.date').datetimepicker({ format: 'YYYY-MM-DD HH:mm', sideBySide: true }); However, with the above format, the year appe ...

The React-Virtualized Autosizer component is returning a height value of 0 when used with VirtualScroll

Despite AutoSizer's width providing the correct value, I am consistently encountering a height of 0 for Autosizer. This is causing the VirtualScroll component to not display properly. However, when using the disableHeight prop and setting a fixed heig ...

In search of grabbing an image from a list item and relocating it to sit before the division tagged with class "event-title"

I am struggling with selecting each list element within the ul and moving the image inside the div class="event-details" above the div with the class="event-title". This adjustment is necessary for achieving the desired styling since the wordpress Event pl ...

populating information to compress using Javascript

I am facing an issue with my button. I want to be able to click on it and have the data populate in the collapse using JavaScript, but for some reason it is not working. The collapse functionality is working fine when I click the button, so there is no pr ...

Tips for implementing the handleChange event with CalendarComponent from the PrimeReact library

Hey there! I'm currently working with the CalendarComponent from the PrimeReact library in my app. I want to update the type of event being typed in the handleChange function instead of leaving it as :any. Can anyone provide some suggestions on what s ...

PHP's `json_encode` is failing to properly convert an array and is outputting `{

My system is running CentOS 7.4 with PHP 5.4 installed. $s='a:91:{s:13:"spotsviewvars";s:7:"1916.74";s:13:"100000T18vars";N;s:17:"100000T18S106vars";s:7:"1746.95";s:17:"100000T18S107vars";s:4:"4.49";s:17:"100000T18S108vars";s:4:"8.29";s:17:"100000T18 ...

Timetable sets anchors raised

Is there a way to set up regular sail lifts? For instance, can sails be scheduled to restart every 12 hours? I am looking to do this to prevent losing connection to the remote database. Thank you ...

Validating HTML using EJS templates set as "text/template" elements

What is the general consensus on HTML validation when utilizing a framework such as Backbone or Meteor and generating views in the client from EJS templates? An issue arises with the fact that name is not considered an official attribute for a <script& ...

Using JavaScript to Set Values and Manage Session State in APEX

Trying to utilize JavaScript in Oracle APEX to set the value and session state. See below function that is being called: function updateItemValue(element) { $s('P2020_SELECTED', element); apex.server.process ('MY_PROCESS', { ...

JavaScript failing to load following PHP header() redirect

I've set up a page that allows users to sign in by filling out a basic form, which then sends the data to a separate PHP script for validation. After the validation process is complete, the PHP script uses the header() function to redirect the user to ...

Error event triggered by Ajax call despite receiving 200 ok response

$.ajax({ url: 'http://intern-dev01:50231/api/language', type: 'GET', dataType: 'json', success: function() { console.log('Success! The call is functioning.'); }, ...

What are the best techniques for concentrating on a kendo maskedtextbox?

What is the correct way to set focus on the kendo-maskedtextbox in TypeScript after the view has initialized? The information provided in Telerik's example here is lacking in detail. ...