"Resolving the problem of populating an empty array with JSON

My JSON structure at the top level is set up like this:

{
    "video": [],
    "messages": [],
    "notifications": []
}

In the database output stored in a variable called "result," I have data that I want to add to the "video" array:

[
    {
        "_id": "5f98ab906439155cfc6f9afb",
        "status": "NOT_STARTED",
        "date": "2020-10-27T23:21:52.683Z",
        "callInvitees": [
            {
                "username": "user1"
            },
            {
                "username": "user2"
            }
        ]
    },
    {
        "_id": "5f98aba0789e163e0c78908f",
        "status": "NOT_STARTED",
        "date": "2020-10-27T23:22:08.048Z",
        "callInvitees": [
            {
                "username": "user1"
            }
        ]
    }
]

This is the code I am using:

let dashboardJSON = { "video": [], "messages": [], "notifications": [] };
dashboardJSON.video.push(result)

The current outcome gives me nested arrays in the "video" section:

{
    "video": [
        [
            {
                "_id": "5f98ab906439155cfc6f9afb",
                "status": "NOT_STARTED",
                "date": "2020-10-27T23:21:52.683Z",
                "callInvitees": [
                    {
                        "username": "user1"
                    },
                    {
                        "username": "user2"
                    }
                ]
            },
            {
                "_id": "5f98aba0789e163e0c78908f",
                "status": "NOT_STARTED",
                "date": "2020-10-27T23:22:08.048Z",
                "callInvitees": [
                    {
                        "username": "user1"
                    }
                ]
            }
        ]
    ],
    "messages": [],
    "notifications": []
}

I want

"video": [ { ... }, { ... } ]
instead of
"video": [[ { ... }, { ... } ]]

How can I fix this issue?

Answer №1

To incorporate the spread operator, you can utilize it in the following manner:

let result = [
    {
        "_id": "5f98ab906439155cfc6f9afb",
        "status": "NOT_STARTED",
        "date": "2020-10-27T23:21:52.683Z",
        "callInvitees": [
            {
                "username": "user1"
            },
            {
                "username": "user2"
            }
        ]
    },
    {
        "_id": "5f98aba0789e163e0c78908f",
        "status": "NOT_STARTED",
        "date": "2020-10-27T23:22:08.048Z",
        "callInvitees": [
            {
                "username": "user1"
            }
        ]
    }
]

let dashboardJSON = { "video": [], "messages": [], "notifications": [] };

dashboardJSON.video.push(...result)

console.log(dashboardJSON);

Answer №2

Utilize the Array.prototype.map() method to efficiently transform elements in an array. The map method creates a new array by applying a specified function to each element.

const result = {
  videos: [],
  messages: [],
  notifications: [],
};

const dataset = [
  {
    _id: '5f98ab906439155cfc6f9afb',
    status: 'NOT_STARTED',
    date: '2020-10-27T23:21:52.683Z',
    callInvitees: [
      {
        username: 'user1',
      },
      {
        username: 'user2',
      },
    ],
  },
  {
    _id: '5f98aba0789e163e0c78908f',
    status: 'NOT_STARTED',
    date: '2020-10-27T23:22:08.048Z',
    callInvitees: [
      {
        username: 'user1',
      },
    ],
  },
];

result.videos = dataset.map((item) => item);
console.log(result);

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

I require the extraction of data from a MySQL database, converting it into a JSON array, and utilizing the array for auto-complete functionality in a text box

I have a task where I need to retrieve data from a MySQL database and transform it into a JSON array. I then want to use this JSON array for autocomplete functionality in textboxes. I know how to achieve this using separate PHP files to fetch the data from ...

Python Selenium- Extract and print text from a dynamic list within a scrolling dropdown element

I am currently working on a project using Selenium and Python to extract a list of company names from a dropdown menu on a javascript-driven webpage. I have successfully managed to reveal the list of company names by clicking the navigation button, and eve ...

What steps should I take to create this animation?

So here's my concept: I envision a circle div positioned in the center with multiple small lines extending outwards, resembling rays of sunlight. How should I go about achieving this effect? Would implementing JavaScript or utilizing CSS3 animations b ...

Instructions on nested keys in iOS for API request

Here is my approach to posting to an API: curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST http://sub.domain.com/api/v1/sections.json -d "{\"section\":{\"properties\":{\"email&b ...

Executing a query with a `has many` relationship in MongoDB: Step-by-step guide

In my setup with Node, Express, and backbone, I am successfully retrieving records from MongoDB collections using simple queries. However, I am struggling to understand how to query more complex data, such as the one below: db.employees.aggregate( [ ...

Unusual conduct when employing basic directive for validation messages

Within my code, I have implemented the following directive: App.directive("validateMsgFor", function(){ return{ templateUrl : "view/templates/validateMsgFor.html", restrict: "E", scope: { field : "=" } ...

Save all dynamically received data from a form in PHP as an array

I have developed a PHP form that dynamically adds new text variables in this manner: <form action="" enctype=”multipart/form-data” method="post" action="<?php echo $_SERVER['REQUEST_URI'];?>"> <div id="div"> va ...

What is the best way to update object values only when changes occur, and leave the object unchanged if no changes

There is an object named ApiData1 containing key-value pairs, including color values within properties. The colors are updated based on the numberOfProjects value from ApiData2, with specific ranges dictating the color updates. This setup is functioning co ...

Vue.js has a feature where it automatically closes the form tag within a for loop

In my Vue.js application, I have created a table where each row is a form with a submit button. This is the code snippet I am using: <div id="admin-user"> <table class="table"> <tr v-for="(user, index) in users"> < ...

The Angular 2 rollup AoT compilation results in a larger build size compared to the standard JiT build

I'm facing an issue with reducing the weight of my app during the building process. I am using Angular 2 seed as a starting point. https://github.com/mgechev/angular-seed When I run: npm run build.prod my app.js file size is 1.5MB. However, when I ...

Utilizing the Jquery ready method in conjunction with the load function

While utilizing the ready() method to access the DOM, I encountered an issue where jQuery was returning undefined when trying to access an element. Even after nesting the ready() function inside $(window).on("load", function()), there were still instances ...

For each error that occurs when there is only one item in the array during a post request

My nodejs server has a JSON schema like this: var UserSchema = new Schema({ nick: String, deviceId: String, visivel: Boolean, checks: [{date: {type:String},log: {type:Number},lng: {type:Number}}] }); In the Post code ...

Using jQuery to retrieve the id with [id^=''] when making an AJAX request, then populating and generating a table based on the retrieved data

In my jQuery code, I am using AJAX to fetch data and then creating a simple table with that data. Here is an example: $.ajax({ method: 'GET', url: '/analyzePage/searchTag/' + tagName, contentType: false, processData: fa ...

Encountering the "Invalid Element Type" error in a Vue Native project right after setting it up

After creating a vue-native project with the command vue-native init henry-pager, I navigated to the directory and initiated the online builder by running expo start. However, when attempting to run it on the web platform, an error message appeared: Error: ...

update confirmed data from a record

I am facing a unique challenge, where I have an edit form that updates a record in a table. One of the fields, let's say username, needs to be unique. To validate this, I am using the jQuery validation plugin along with the remote method as shown belo ...

Bug causing connection issues in Node.js when dealing with IP redirection

I recently encountered an issue with NodeJS while using a kafka node on a node-red instance installed on my RPI3. Let me paint you the scenario: I have a cluster set up with a functioning Kafka instance. The machine hosting the Kafka broker has a private ...

Having trouble decoding a potentially JSON string in Laravel controller without throwing any exceptions

After printing the results of \Input:all() in the laravel.log, I noticed the following output: Input : {"val":{"postID":"22","tags":["3"],"forwardComment":"aaaaaaa"}} [] It appears to be JSON format, so I attempted to decode it using json_d ...

The intricate field name of a TypeScript class

I have a TypeScript class that looks like this - export class News { title: string; snapshot: string; headerImage: string; } In my Angular service, I have a method that retrieves a list of news in the following way - private searchNews(sor ...

Leveraging JavaScript to generate a downloadable PDF document from the existing webpage

My goal is to have the user click a button labeled 'View PDF' or 'Download PDF' on the current webpage. This button would then execute JavaScript code to generate a PDF based on how the current page appears. I attempted using jspdf for ...

Uploading files with Angular and NodeJS

I am attempting to achieve the following: When a client submits a form, they include their CV AngularJS sends all the form data (including CV) to the Node server Node then saves the CV on the server However, I am encountering difficulties with this proc ...