Converting an array into JSON format in JavaScript without duplicate curly braces

Having two parallel mysql queries in node js is meant to retrieve data more efficiently. The following javascript code reads from a mysql database and stores the results in a javascript object:

async.parallel({
    aaChannelsCount: function(cb) {
    /* GET - channels */
    pool.query("SELECT JSON_LENGTH(sort) AS channels FROM channels WHERE bouquet='[\"?\"]'",[rows[0].bouquet], function (err, rows, fields) {
    /* CHANNELS - count */
    if (rows.length) {
        data.push( {"channels": rows[0].channels, "radio": 0} );
            };
        });
    },
    aaVideoClub: function(cb) {
        /* GET - videoclub */
        pool.query("SELECT count(id) AS videoclub FROM vod", function (err, rows, fields) {
            /* VIDEOCLUB - count */
            data.push( {"videoclub": rows[0].videoclub} );
            res.json(data); 
        });
    }
    }, function(err, results) {
        if (err) { 
            /* SHOW - unauthorized */
            res.sendStatus(401);
        } else {
            res.json(data);
        }
    }
    );

The current output obtained using res.json(data) is as follows:

[{"channels":3,"radio":0},{"videoclub":2}]

However, the desired output is like this:

{"channels":3,"radio":0, "videoclub":2}

In the code, data.push is used to add results from mysql into a javascript array object, which is then converted into json. However, the desired output has not been achieved yet.

Answer №1

If you want to convert an array into parameters, you can utilize Object.assign along with the spread syntax ....

var array = [{ channels: 3, radio: 0 }, { videoclub: 2 }],
    object = Object.assign(...array);
    
console.log(object);

Another approach is to assign properties directly by working with an object. Instead of:

if (rows.length) {
    data.push( {"channels": rows[0].channels, "radio": 0} );
}

You can create an object and assign its properties like this:

var object = {};

if (rows.length) {
object.channels = rows[0].channels;
object.radio = 0; 
}

Remember, after a block statement { ... }, there's no need for a semicolon.

Answer №2

Follow these steps to accomplish it:

const data = [{"channels":3,"radio":0},{"videoclub":2}];

const output = {};
for(const item of data){
    for(prop in item){
        output[prop] = item[prop];
    }
}

console.log(output);

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

What is the process for creating an index signature for a type alias representing a Map in Typescript?

Suppose I have a custom type for a Map as follows: type MyCustomMap = Map<string, number>; Is there any way to add an index signature to this type so that I can set key-value pairs after initializing it? I have been able to achieve this with types ...

Transmit a lexicon containing values encapsulated within a roster to an AJAX solicitation, endeavoring to dissect it at the receiving

My goal is to send a dictionary that looks like this (values in a list): datax = { "name": ["bhanu", "sivanagulu","daniel"], "department": ["HR", "IT", "FI"]} In ...

Rendering the HTML5 canvas within a console environment

I am looking to create images of humans on the console using nodejs. In order to achieve images of higher quality, I require a library or module that can facilitate drawing images in the console. Some options available include imaging and console-png. How ...

Building an Express API using ES6 script: A Step-by-Step Guide

After creating a no-view REST API using the express generator, I decided to convert everything to ES6 script and compile it with Babel. However, upon entering localhost after the changes, an error message appeared: No default engine was specified and no ...

Use JavaScript to convert only the initial letter to uppercase

Once again, I am in the process of learning! Apologies for the simple questions, but learning is key... Attempting to implement a trick I found online to change all letters to uppercase, I am now trying to adjust it to only capitalize the first letters. T ...

Guide on incorporating factories with Ionic/Angular JS while utilizing phonegap

I've been experimenting with global variables in my ionic/angular + phonegap app project by implementing a factory service. However, even adding a simple factory service like the one below somehow disrupts the app and causes all screens to turn compl ...

Accessing JSON data from the Public folder in a create-react-app

I have a JSON file called ipAddress.json with the following content: { "ipAddress": "11.111.111.111" } To access this file, I placed it in an "ipAddress" folder within the public directory. So now the path is "public/ipAddress/ipAddress.json". However, ...

Swap the text within the curly braces with the div element containing the specified text

I have an input and a textarea. Using Vue, I am currently setting the textarea's text to match what's in the input field. However, now I want to be able to change the color of specific text by typing something like {#123123}text{/#}. At this poin ...

Error encountered during automatic form submission

My current project involves creating a web notepad that automatically saves changes every minute. The notes are stored in a field called "notas" for each user in the database. Here is some of the code I am using: <html> <head> < ...

Learn how to display a tooltip for every individual point on a Highcharts network graph within an Angular

I am currently working on developing network graphs using highcharts and highcharts-angular within my Angular application. I have successfully managed to display the graph with datalabels, but now I need to implement tooltips for each point or node on the ...

Unlocking the Potential of Scala: Streamlining Code with Play Framework and JSON

Consider the case class provided below... case class Address( name: Option[String], zip: String, city: String ) ... I am looking to generate distinct JSON outputs based on whether or not name is specified: val selector = address.name.map { address ...

Is it possible to use next.js to statically render dynamic pages without the data being available during the build process?

In the latest documentation for next.js, it states that dynamic routes can be managed by offering the route data to getStaticProps and getStaticPaths. Is there a way I can create dynamic routes without having to use getStaticProps() and getStaticPaths(), ...

Prevent zooming or controlling the lens in UIWebview while still allowing user selection

Is there a way to disable the zoom/lens on uiwebview without affecting user selection? I'm trying to avoid using "-webkit-user-select:none" in my css. -webkit-user-select:none ...

Obtain geographical information from Google Maps using PHP

I am interested in creating a PHP function that will generate a json_encoded list of all restaurants near a specified point. The function should take parameters such as Latitude, longitude, and radius (in meters) to return the desired json_encoded list. ...

Babel is failing to transpile the Modal component from material-ui-next to ES5

Issue with Babel transpiling Modal component from material-ui-next Here is my .babelrc configuration: { "presets": ["es2015", "react", "stage-1", "stage-2", "stage-3"] } This is the webpack-config.js setup: var webpack = require('webpack'); ...

"Is there a virtual keyboard available that supports multiple inputs and automatically switches to the next input when the maximum length

Looking to build a virtual keyboard with multiple inputs that automatically switch to the next input field after reaching the maximum length. Currently having an issue where I can only fill the first input and not the second one. Any assistance in resolvin ...

Attempting to make initials fade and slide out upon mouseover using jQuery

I've been experimenting with jQuery to create a unique effect where hovering over my initials in the header expands the containing div and reveals my full name letter by letter. However, I'm facing some challenges and could use some guidance on t ...

What is the correct location to define the "env" setting in the eslint.config.js file?

In 2022, ESLint rolled out a new configuration system called the "flat config" here. Check out the documentation for the new "flat config". | Old configuration system documentation here. The "flat config" documentation shows that the `eslint.config.js` ...

The mystery behind React rendering twice, even when React strict mode is disabled

My code is error-free, but React seems to render this component twice for some reason. I can't figure out why. Here is an image showcasing the issue: https://i.stack.imgur.com/hKvug.png Index.js Page : import LandingPage from '../components/Ho ...

Angular Tip: Display data in a dropdown using a select element

When I have two select elements and want to display values if they exist: page.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app ...