What is the best way to add elements into a nested array using JavaScript?

Below is an example of the JSON structure I am working with:

{
    "categories": [{
        "type": "Fruits",
        "items": [{
            "name": "Apple"
        }, {
            "name": "Banana"
        }, {
            "name": "Orange"
        }, {
            "name": "Grapes"
        }]
    }]
}

I have successfully extracted the category Fruits from this JSON and stored it in a new array. Now, I am trying to add the items under Fruits such as Apple, Banana, and Orange into the same array following the same hierarchical structure as the original JSON.

I attempted to use the categories[0].items.push method to add the innermost item, but that has not been successful. I have already separated the values of the name key from the JSON object and placed them in another array. I am seeking guidance on how to efficiently add these values to a new array while maintaining the original structure.

Answer №1

The solution provided will not work due to the attempt to push into an object literal. To resolve this issue, consider using the following approach:

let newObject = {
    "sections": [{
        "title": "Technology",
        "categories": [{
            "name": "Mobile Devices",
            "items": [{
                "label": "Device1"
            }, {
                "label": "Device2"
            }, {
                "label": "Device3"
            }]
        }]
    }]
};

newObject.sections[0].categories[0].items.push({ label: "Device4" });

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

Extract the JSON information and determine the frequency of each data item

I am looking to extract the json data and retrieve the count for Leadstage. Specifically, I aim to obtain the leadstage count based on geographical location. { "Geo" :"US East" "LeadStage": "SGL", &quo ...

How can I properly retrieve an entry for processing within my route?

Hello everyone! This is my first question on this platform, so please bear with me if I'm missing any important details. I'll add them as soon as possible. I am currently working on setting up a camel route where I retrieve a URL from my Databas ...

Vue enables components to be used in any part of the application, not limiting them to

Currently, I am initializing my Vue instance in the following manner: import ListClubsComponent from "./components/clubs/list-clubs.vue"; new Vue({ el: "#app", components: { "list-clubs": ListClubsComponent } }); It seems to be functi ...

How to handle Object data returned asynchronously via Promises in Angular?

Upon receiving an array of Question objects, it appears as a data structure containing question categories and questions within each category. The process involves initializing the object with board: JeopardyBoard = new JeopardyBoard();. Subsequently, popu ...

Trying to call the Wia class constructor without using the 'new' keyword will result in a TypeError

I'm having trouble running my code from a JSON file, as it's throwing this error message at me: TypeError: Class constructor Wia cannot be invoked without 'new'at Object. (/home/pi/wia-pi-camera/run-camera.js:3:25) 'use strict&apos ...

Retrieve information from a URL within the same domain by utilizing jQuery, then add it to a div

I have a website that utilizes Cloudflare services. I can access basic information such as user IP, user agent, and the specific Cloudflare server being used to direct my website traffic at this URL: https://www.example.com/cdn-cgi/trace (you can also view ...

Pulling information from a JSON response using Python while omitting certain specified data

In my Python shell, I'm working with the following json_data: [{u'alt_name': u'JON~1.EXT', u'attributes': [u'DIRECTORY'], u'create_time': 1538729344, u'filename': u'Jon.Doe', u&apo ...

Update and modify content.php directly on the samepage.php rather than through externalpage.php by utilizing either Jquery or AJAX

Is there a preferred method for loading content on the same page instead of redirecting to an external page using AJAX or JQuery? Below is an excerpt from my external.php file: $id = null; if (!empty($_GET['id'])) { $id = $_REQUEST[ ...

Determine the number of rows in a specific column using a Java array in MySQL

I'm facing an issue with my Java program. I have an array of strings and a database with the same strings stored in either column A or column B. I need to determine whether each element in my array corresponds to column A or column B in the database. ...

Using Vue.js to showcase real-time Pusher data in Laravel 5.4

I am currently working on developing a real-time chat application using vue.js, Pusher, and Laravel. I have successfully managed to receive information from Pusher, as I can view the JSON data in the console with the correct details. However, I am facing a ...

Using Vue.js transitions within a loop

I am facing an issue with a transition in Vue.js where only the leave transition is working and not the enter transition. Here is my code: <template v-for="(item, index) in imagesList"> <transition name="fade"> <div class="ctn"> ...

Replacing an array element in React.js

Here is a React.js code snippet where I am trying to utilize an array called distances from the file Constants.js in my Main.js file. Specifically, I want to replace the APT column in the sampleData with a suitable value from the array distances extracted ...

What are the best techniques for improving the efficiency of array chunk copying in C#?

I'm in the process of developing a real-time video imaging application and I'm looking to optimize this particular method. Currently, it takes approximately 10ms to execute, but I am aiming to reduce that time to 2-3ms. After experimenting with ...

Working with CURL involving a specified port and extra parameters within the URL, as well as JSON data

Recently, I stumbled upon a URL with an interesting format: http://www.domain.com:10001/api/Data.cgi?Scope=System This URL contains a JSON dump that I need to parse. However, as someone who has previously only used get_file_contents, I am struggling due t ...

Incorporate a refresh button into the JSON table view that includes an activity

How can I implement a refresh button in my app that displays an activity indicator when pressed? I have written the following code: In this app, I am using JSON to retrieve data from a server and I want users to see updated content when they press the re ...

The webpage continues to refresh after executing a JavaScript function triggered by the AJAX response

I have experimented with various solutions for calling a JavaScript function returned from an AJAX response. While each method worked to some extent, I found that using an alert within the refreshResults function was necessary in order to display the resul ...

Interrogating MYSQL database field with longtext storage containing JSON format

I have a table structured like this: CREATE TABLE `Event` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `created` datetime(6) NOT NULL, `last_updated` datetime(6) NOT NULL, `info` longtext NOT NULL, PRIMARY KEY (`id`) ) ...

Expanding a string by adding numeric characters using JavaScript Regular Expressions

Can you increment a numeric substring using regex/replace? For example, if the end of a string (like window location) contains #img-{digit}, is it possible to use regex to replace the digit with +1? I know how to match the hash, but extracting the number, ...

A guide on effectively parsing a hefty JSON file with Python's ijson module

Currently, I am facing a challenge in parsing a massive JSON file (measuring hundreds of gigs) to extract data from its keys. To illustrate, let's take a look at the sample scenario below: import random, string # Generating a random key def random_ ...

Can you send JSON data and redirect simultaneously using Express?

In my application, there is a registration feature that involves sending a confirmation email to the user. I am looking to achieve a similar outcome as shown below: return res.status(200).redirect('/').json({ message: 'Successfully confir ...