How can I efficiently transform JSON fields into arrays using JavaScript?

Looking for a method to transform the content of a JSON file where each field is replaced with an array?

{
    "ID": "GO:0051345",
    "Description": "positive regulation of hydrolase activity",
    "GeneRatio": "3/5",
    "BgRatio": "464/15405",
    "pvalue": 0.000259498331261799,
    "p_adjust": 0.0446337129770295,
    "qvalue": 0.0169356805665595,
    "geneID": "Ptpa/Wdr35/Dnajb11",
    "Count": 3
}

The following code accomplishes this task:

GO_data = fs.readFileSync('my_data.json');
GO_data = JSON.parse(GO_data);
var data_header = Object.keys(GO_data);
// Enumerate its property names
for (var prop in GO_data) { 
    var arr = [];
    arr.push(GO_data[prop]);
    GO_data[prop] = arr;
}
// Write the converted JSON
fs.writeFileSync('my_data_arr.json', JSON.stringify(GO_data), 'utf8');

After transformation, the content of 'my_data_arr.json' appears as desired:

{
    "ID": [
        "GO:0051345"
    ],
    "Description": [
        "positive regulation of hydrolase activity"
    ],
    "GeneRatio": [
        "3/5"
    ],
    "BgRatio": [
        "464/15405"
    ],
    "pvalue": [
        0.000259498331261799
    ],
    "p_adjust": [
        0.0446337129770295
    ],
    "qvalue": [
        0.0169356805665595
    ],
    "geneID": [
        "Ptpa/Wdr35/Dnajb11"
    ],
    "Count": [
        3
    ]
}

If you have any suggestions for a better or faster approach, please share!

Answer №1

Instead of creating an array and pushing values into it one by one, you can simplify the process by using an array literal with the value inside:

for (let key in myData) {
    myData[key] = [myData[key]];
}

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

On Windows systems, where exactly does npm place its packages during installation when using Node version 10.x

Does anyone know where I can locate the locally installed npm modules when using NodeJS version 10? I have checked under C:\Users\MyUser\AppData\Roaming, but I cannot find the "npm" folder. ...

How to identify a button click on an HTML page within an Android WebView

When using my Android app, I encounter an issue with a webview that contains a form and a submit button. The button code snippet is as follows: <button role="button" class="btn ng-binding" ng-click="actions.collect()" tooltip="default" title="Check f ...

Identify when a request is being executed using AJAX by checking the URL

My current code includes multiple ajax requests from various JavaScript files. I am looking for a way to identify specific ajax requests and interrupt their execution in order to prioritize a newer one. Is it possible to detect and stop ajax requests based ...

The functionality of one button triggering the opening of two dropdown menus simultaneously is being successfully implemented

My issue is that I have created two different dropdowns, but they both open the same dropdown menu. Here is my code; <div class="d-flex"> <button class="btn btn-icon btn-group-nav shadow-sm btn-secondary dropdown-toggle" type="butto ...

When a <a href> link is clicked, the Struts action should open as a popup

I have a form on my jsp page, <form action="test1_action" name="test" method="post" id="test"> Additionally, I have two distinct links: link1 and link2. When link1 is clicked, the form should be submitted with the action test1_action. $('#l ...

Utilize focusout and onclick events on multiple components at the same time

Currently, I am in the process of coding an Autocomplete feature from scratch in Vue, but I am encountering a challenge when it comes to selecting an option from the dropdown menu. I have set it up so that the dropdown is shown when the input is clicked ...

Creating a framework for sharing data between directives using Angular services

In my project, I have developed two directives named "mainPane" and "sidePane" displaying lists of items. These lists often contain overlapping content, allowing users to interact with the items in either list. My main requirement is that any changes mad ...

Are there any find all functions available in JavaScript that are built-in?

I frequently work with arrays in JavaScript, and I am facing an issue with the function .find() as it only returns the first occurrence. I need a way to get all occurrences if there are multiple. Below is my code: const condition = [ { info_p ...

Angular 2/webpack error: Unable to find require reference

I have integrated an HTML template from a graphic design company into my Angular 2 project using node and webpack. This HTML template includes various scripts like: <script src="js/jquery.icheck.min.js"></script> <script src="js/waypoints. ...

Start a Draft.js Editor that includes an unordered list feature

I am trying to pre-populate a draft.js editor with an unordered list made from an array of strings. Here is the code I have so far: const content = ContentState.createFromText(input.join('*'), '*') const editorState = EditorState.crea ...

How can I troubleshoot the issue with my browser not connecting through the proxy with NuxtJS and Axios

While server rendering is functioning as expected with the proxy, a discrepancy arises when the request is made from the browser. In server-side rendering, the request goes to custom-server.com/v1/places, whereas in the browser it goes to current-domain.co ...

When the tab on my website is clicked, the fontawesome icons elegantly transition into their designated positions

When my website loads, some of the fontawesome icons pop in after the animations finish. Specifically, two out of four icons used for visual representation of my skills (such as 'Sound Design' with a headphones picture) pop in when it gets to the ...

What is the best way to store JSON encoded items in an array using square brackets?

Currently, I am utilizing Javascript along with NodeJS to dynamically generate an array of JSON objects. My goal is to store this array of JSON objects in a .json file for future reference. However, when I attempt to save the file, I encounter an issue whe ...

Creating a dynamic mongoDB query string for field selection in a JavaScript application: A step-by-step guide

I am currently working on a Node.js application that utilizes MongoDB. The schema for my customers collection is as follows: { '_id' : 1234341264876876143 , 'profile':{ 'name': 'bob', &ap ...

Is it possible to run a JavaScript script from any location?

Currently, I am diving into a Javascript script and in order to run it seamlessly from any webpage I am browsing, I am thinking of adding a button to my bookmarks or using an extension. To be honest, I am clueless about the process and despite doing some ...

The web method is not activated

My initial endeavor to call a server-side function from JavaScript is not yielding results as the webmethod is not being invoked. Within the aspx file, there is a bootstrap-styled button; upon clicking it, the objective is to append a new entry to the use ...

webpackDevMiddleware does not automatically trigger a reload

Currently, I have implemented webpack dev middleware in my project like this: const compiledWebpack = webpack(config), app = express(), devMiddleware = webpackDevMiddleware(compiledWebpack, { historyApiFallbac ...

Utilize Javascript and JQuery to implement sending a custom header in an OPTIONS preflight API request

Snippet: $.ajax({ type: 'GET', dataType: 'json', url: api, xhrFields: { withCredentials: true }, beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', "Basic [my auth token]"); }, ...

The functionality of the Bootstrap toggle button seems to be malfunctioning

I'm having trouble with the toggle button in my Bootstrap code. When I resize the window, the toggle button appears but clicking on it doesn't do anything. This is my first time using Bootstrap, so I might have made some silly mistake. Any assist ...

Tips for determining if a player (canvas) is in contact with a drawn wall for collision detection

I created a 2D map using the canvas HTML element where I drew a red square to represent the player and a light blue wall underneath it. I am looking for a way to detect if the player (red square) is in contact with the wall (light blue). The elements do no ...