One way to add a JSON object to an empty JSON array using Javascript involves pushing

Currently, I am facing an issue with an empty JSON array.

shoppingCart: []

In addition to the empty array, I also have a JSON object defined as follows:

let product = {"name": "name", "price": "price", "quantity": "quantity", "logoPath": "logoPath"};

My objective is to add this JSON object to the existing array. To achieve this, I have written the following code snippet:

let obj = JSON.parse(state.shoppingCart);
obj.push(product);
state.shoppingCart = JSON.stringify(obj);

Despite my efforts, I encountered the following error message:

"SyntaxError: Unexpected end of JSON input"

Ultimately, I aim to populate the empty array with multiple objects like the example shown below:

shoppingCart: [{id: 1, name: name1}, {id: 2, name: name2}, {id: 3, name: name3}]

Can you please help me identify where I may have made a mistake in my approach?

Answer №1

Don't waste time trying to JSON.parse() the variable shoppingCart

let shoppingCart = []

let product = {
  "name": "name", 
  "price": "price", 
  "quantity": "quantity", 
  "logoPath": "logoPath"
}

//let obj = JSON.parse(shoppingCart)
shoppingCart.push(product)
shoppingCart = JSON.stringify(shoppingCart)

console.log(shoppingCart)

Answer №2

It seems like there may be some confusion in understanding the question, but if you're looking to create an array of JSON objects, you can do something similar to this:

let jsonArray = [];
let object1 = {"name": "example1", "price": 1, "quantity": 1, "logoPath": "path1"};
let object2 = {"name": "example2", "price": 2, "quantity": 2, "logoPath": "path2"};
jsonArray.push(object1);
jsonArray.push(object2);
console.log(jsonArray);

I hope this explanation is clear and helps.

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

The positioning of images on the fabricjs canvas seems to be unreliable and inconsistent

When trying to place a series of 4 images at specified coordinates in fabricjs, I am facing inconsistencies with their placement upon page load. Refreshing the page usually resolves the issue, but I want to prevent this from happening altogether. If anyon ...

Header frame is not valid

I have been working on developing a real-time application using NodeJS as my server and Socket.IO to enable live updates. However, I encountered an error message that reads: WebSocket connection to 'wss://localhost:1234/socket.io/?EIO=3&transpo ...

I encountered an error while decoding JSON: Expecting the property name to be enclosed in double quotes at line 1, column 2

import json import re import scrapy import ast class Scraper(scrapy.spiders.Spider): name = 'scraper' #mandatory=None def __init__(self, page=None, config=None, *args, **kwargs): self.page =page self.config = json.load ...

Which is more effective: Layering multiple canvases in the DOM or consolidating all drawing on a single canvas?

In my previous projects, I have had experience working with layered canvases. While some of my colleagues swear by this approach, I find myself skeptical about its effectiveness. My primary concerns are: If multiple canvases are layered and one undergoes ...

Acquire the jQuery cookie with the power of AngularJS

I am currently utilizing jquery.cookie v1.4.1 to set a cookie in the following manner: $.cookie('userCookie', $("#user").val()); The value returned by $("#user").val() is typically something like 'username' Now, within an angular app ...

Need assistance in retrieving JSON array items without using mapping or a list view in React Native

{"vertical_menu":[{"id":5,"name":"Sidebar Menu 1"},{"id":6,"name":"Sidebar Menu 2"}],"horizontal_menu":[{"id":7,"name":"Menu Item 1"},{"id":8,"name":"Menu Item 2"},{"id":9,"name":"Menu Item 3"}]} After successfully parsing the JSON array above, I used this ...

Having trouble removing a cookie in express?

Seems pretty straightforward. In the /user/login route, I set a cookie as shown below: if (rememberMe) { console.log('Login will be remembered.'); res.cookie('user', userObj, { signed: true, httpOnly: true, path: '/' ...

In Visual Studio, make sure to include a reference to AngularJS.min.js within another JavaScript file

In my AngularJS app, I am utilizing Visual Studio with separate folders. The AngularJS-min.js file is located in a different folder. My query is how can I correctly reference the AngularJS-min.js file in my app's JavaScript file to enable auto-suggest ...

Exploring new options to deduct time from Kendo UI timepickers without relying on Javascript

My current project involves an Asp.net MVC 4 application that includes a Time entry screen. This screen utilizes various Kendo controls and Razor Html helpers to enhance the user experience, such as: @(Html.Kendo().TimePickerFor(m => m.StartTime).Name( ...

Leveraging reframe.js to enhance the functionality of HTML5 video playback

I'm struggling with using the reframe.js plugin on a page that includes HTML5 embedded video. When I try to use my own video file from the same folder, it doesn't work as expected. While everything seems to be working in terms of the page loadin ...

Utilizing the json_encode() function in PHP and JSON.parse() method in JavaScript for handling file data interchange

Utilizing json_encode() in PHP to store an array in a file, then leveraging JSON.parse() in JavaScript on the client side to read the json encoded file and pass it as an array to a sorting algorithm: The result of my json_encode() operation in the ...

How to build a unique ajax call function using a single object parameter in jQuery and JavaScript

Can someone provide a code example for the following requirements: A custom JavaScript function that takes a single object as its argument Utilizes jQuery's ajax method to make an AJAX call The object argument must specify all possible values that c ...

How to Deserialize JSON Objects with Named Items in C# Arrays

Deserialization of JSON data is needed in this scenario: "response": { "records": { "record-1": { "id": "1", "name": "foo" }, "record-2": { "id": ...

State in Vuex is failing to update effectively when actions are being utilized

I'm trying to wrap my head around VueX, but I'm having trouble getting Axios to work with it. In my store.js file, I have the following setup: state: { cards: [], currentPage: 1, lastPage: 2, }, actions: { loadGradients(page ...

I am having trouble locating my TypeScript package that was downloaded from the NPM registry. It seems to be showing as "module not found"

Having some challenges with packaging my TypeScript project that is available on the npm registry. As a newcomer to module packaging for others, it's possible I've made an error somewhere. The following sections in the package.json appear to be ...

I am unable to get the radio button checked in Angular 2

I have set up a form with two radio buttons for gender selection, and I want to ensure that the previously selected option is displayed as checked. Here's the code snippet I've added in my template: <div class="form-group"> <label& ...

Develop a dynamic button using JavaScript to fetch information from an array

I'm struggling with incorporating this button creation code into my HTML using JavaScript. The code for creating the button element in JS file looks like this: var numery = ['A','B','C']; var numer = document.createE ...

Are there any CSS hacks available to address the combination of position: sticky and overflow within the parent element?

I've encountered a sticky position issue when the overflow property is set to auto on a parent element. I've tried various solutions like adding an extra wrapper or using clip instead of auto, but none have worked. While I did find a solution usi ...

Use `jq` to select the initial element following a sort for uniqueness

My task involves managing an array of wireless access points along with their signal levels. I need to extract unique SSIDs with the highest signal strength. # cat aps.json { "AP" : [ { "SSID" : "Bart", "Signal" : -20 }, { "SSID" : "Lisa", "Si ...

"Implementing JavaScript Validation for Textboxes: A Step-by-Step Guide

I need some help with restricting the input of a textbox within a gridview to only 'X' or 'O'. I am not very familiar with javascript, so any guidance on how to accomplish this would be greatly appreciated. It's worth noting that t ...