Issue encountered while attempting to insert a JSON object into a JSON local storage

I am attempting to insert a JSON object into another JSON object that is stored in local storage, but I am encountering an error saying "Object # has no method 'push'".

The JSON object stored in local storage is:

shops {
        "c": [
            {
                "cliente_id": "12",
                "cliente_name": "Vermut",
                "cliente_url": "vermut",
                "categoria_name": "Restaurantes",
                "imagen": "1364.jpg",
                "telefono": "456987123",
                "descripcion": "El mejor sitio en el centro",
                "latitud": "41.3865749",
                "longitud": "2.1745545999999",
                "direccion": "Carrera",
                "porcentaje": "50",
                "distancia": "0.0764"
            },
            {
                "cliente_id": "92",
                "cliente_name": "mexicano",
                "cliente_url": "mexicano",
                "categoria_name": "Restaurantes",
                "imagen": "135.jpg",
                "telefono": "",
                "descripcion": "Comida a\r\n\r\nNuestros . \r\n",
                "latitud": "3.9999",
                "longitud": "6.9999",
                "direccion": "Mexicana",
                "porcentaje": "50",
                "distancia": "0.771095"
            }
        ]
    }

This is the code where I am trying to merge the two JSON objects together. What could be causing the issue?

    function addItem() {
    // Retrieve the existing object
        var oldCli = JSON.parse(localStorage.getItem('shops')) || [];  
        var newCli = {
        "c": [
            {
                "cliente_id": "1",
                "cliente_name": "Restaurante Quebracho",
                "cliente_url": "restaurante-quebracho",
                "categoria_name": "Restaurantes",
                "imagen": "1355.jpg",
                "telefono": "123654469",
                "descripcion": "Quebrachos",
                "latitud": "5.3456",
                "longitud": "2.1264",
                "direccion": "Ronda Quebracho",
                "porcentaje": "25",
                "distancia": "0.4273"
            },
            {
                "cliente_id": "2",
                "cliente_name": "Malinche",
                "cliente_url": "disco-malinche",
                "categoria_name": "Discotecas",
                "imagen": "13493.png",
                "telefono": "234567",
                "descripcion": "Malinches.",
                "latitud": "6.98765",
                "longitud": "1.23456",
                "direccion": "C Malinche 42",
                "porcentaje": "30",
                "distancia": "1.0994"
            }
        ]
    };

        oldCli.push(newCli);

        localStorage.setItem('shops', JSON.stringify(oldCli));
    }

Answer №1

Ensure that you are using the correct syntax when calling the push method on the shops object rather than the c array. Consider this alternative approach:

var oldCli = JSON.parse(localStorage.getItem('shops')).c || [];  

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 insert empty values into keys, then proceed to add nested values in Python

I am currently working on creating a dictionary and populating it with elements in a specific format: {{"source1": { "destination11": ["datetime1", "datetime2", ....]} { "destination12": ["datetime3", "datetime4",....]} ........... ...

Tips for placing a component at the top of QML views

Seeking advice on how to add a QML Menu component to the top of all views in order to achieve a cohesive look and feel similar to that of a typical webpage menu. Any suggestions on how I can accomplish this? import QtQuick 1.0 Row { width: 500 ...

Looking for ways to enhance the optimization and performance of Django ORM queries

Currently, I am developing an API in Django 1.4.5 that sends JSON data to a third-party application. The method I am using to retrieve the data is taking longer because I need related data to be included in the JSON response. def get_speakers(request) ...

Retrieving the chosen item from Angular 2 Material Autocomplete - ensuring it is a valid selection

I am trying to find a way to save the selected value of an Angular Material AutoComplete component into a variable within the corresponding component. Unfortunately, using [(ngModel)] directly on the input is not an option since it would allow any user in ...

Errors are being thrown by 'npm run serve' due to the absence of FilterService

I've been working on a project using Vue.js and I keep running into an issue with npm. Every time I install it, I get errors saying that certain files are missing from the node_modules folder. When I try to run npm run serve, I encounter the followin ...

Having trouble accessing collections by date using mongoose

I am struggling to filter a collection by date in my query Below is the code snippet I have been working on: //Snippet of my schema: date: {type: Date, required: true} //Date stored in MongoDB: date: 2019-09-06T16:48:14.000+00:00 / ...

Pass the identifier to another component in Vue

Connecting with the Community Within my application, I showcase a list of doctors in the DoctorView component using the following code: <div class="col-12 m-2" v-for="recommendation in recommendations" :key="recommend ...

Trouble encountered when submitting a form with Reactjs

I am currently working on Reactjs (Nextjs) and I am facing some issues while trying to submit a form. Can anyone provide me with guidance on how to properly submit form data? Below is the snippet of my current code: export default function Home() { ...

The navigation menu is obstructing the website content in mobile view

I am facing an issue with the navigation menu on my website. When I switch to mobile resolution to test responsiveness, the menu ends up overlapping the website content. How can I fix this problem? Below is a screenshot of the current situation. Screenshot ...

Managing failure function in AJAX: A comprehensive guide

I've been trying to manage the failure function in AJAX to display specific messages to users. Despite attempting various solutions, I have struggled to control the failure function. Here is my code: <p id="Likes" class="alert-danger" style="displ ...

Take users to another page upon form submission

I'm working on a React form using Typescript and Material-UI. Here's an example: import React, { useState } from "react"; import TextField from "@material-ui/core/TextField"; import { createStyles, makeStyles, Theme } from &qu ...

The Bootstrap modal fails to appear when closed

After opening and closing the modal window, clicking on the button does not display the modal window again. The screen remains grayed out and the content of the modal window does not appear. yyyyyyyyyyyyyyyy function customShortcode() { ob_start(); ...

Ways to obtain the selected value within a td element

I need help with extracting the value of a selected option from a table. <tr class="table-info" id="tr1"> <select class="form-control"> <option>foobar</option><option>foobar2</option> </select> ...

Function returns to execute another Function

Update: Is there a way to retrieve a value from a nested function and have it returned by the parent function? function returningFn() { function otherFn() { var value = 123; return value; //To be retrieved by returningFn } } I nee ...

What is the best way to incorporate additional elements into an array without replacing the original one?

I'm having a problem adding new elements to an Array as it seems to keep overwriting the first element. I'm not quite sure if my coding approach is correct, but here is the code snippet: // Both name and age are assigned values from NgModel thi ...

Exploring the Depths of JSON Arrays within Typescript

I am faced with a challenge in extracting the value of the "id" from the following array of JSON data. The issue lies in the fact that the value is enclosed within double square brackets "[[" which are causing complications in retrieving the desired result ...

A list of checkboxes created with jQuery

I am experiencing an issue with a series of checkboxes. Their default behavior has been unexpectedly altered, preventing me from checking them. However, the purpose of using this jQuery was to highlight the surrounding li elements when the checkboxes are c ...

Is there a way to display CakePHP database query results without table names, similar to how it's done in MySQL?

Currently, I am working with cakephp and I have a model set up. $db = $this->getDataSource(); $result = $db->fetchAll( 'SELECT table1.id, table1.title, table1.buy_url, table2.image_file as image, ...

Set the key for all elements in a sibling array to be the same key

Here is a sample input JSON: { "some_key": "x", "another_key": "y", "foo_id": 123, "all_foo": [ { "foo_name": "bar1" }, { "foo_name": & ...

What methods can be utilized to avoid displaying a Bootstrap popover intermittently within an AngularJS framework?

When using the bootstrap popover in a custom AngularJS directive, I need to display an error message when the button is disabled by setting $scope.buytypeButton= {type:false}. The error message should be displayed in a popover. On the other hand, when $sco ...