Changing the Structure of a JSON Data Object

After using Papa Parse to generate a JSON from a CSV file, the structure of the JSON appears as follows:

{ object, object, object, .... , object }

Now, I have a requirement to transform this JSON into the following format:

{ "publication" : 
    {
      "id" : 1,
      "name" : "name1"
    },
  "publication" :
    {
      "id" : 2,
      "name" : "name2"
    },
  "publication" :
    {
      "id" : 3,
      "name" : "name3"
    }
}

Each occurrence of "publication" should have properties like "id" and "name" nested within it.

To make this transformation using JavaScript, we can loop through each object in the original JSON and create a new JSON that conforms to the desired structure.

Thank you.

Answer №1

A common issue arises when attempting to use multiple keys with the same name...

One solution is to store them in an array

{ 
    "items" : [
      {
        "id" : 1,
        "name" : "item1"
      },
      {
        "id" : 2,
        "name" : "item2"
      },
      {
        "id" : 3,
        "name" : "item3"
      }]
}

Answer №2

Could this possibly be a collection of published works?

{ publishedWorks: [{"id":1, "title":"Title1"},
                  {"id":2, "title":"Title2"} ... ]}

Answer №3

It seems like you're looking to reformat your objects as shown below:

{"publication" : { "id" : 1, "name" : "name1" }
{"publication" : { "id" : 2, "name" : "name2" }
{"publication" : { "id" : 3, "name" : "name3" }

In order to achieve the desired structure:

{ "publication" : [ 
    {
        "id" : 1, 
        "name" : "name1"
    }, 
    {
        "id" : 1, 
        "name" : "name2"
    }, 
    {
        "id" : 3, 
        "name" : "name3"
    } ] 
}

You can use the following code snippet:

var json = [{"publication" : { "id" : 1, "name" : "name1" }},
                {"publication" : { "id" : 2, "name" : "name2" }},
                {"publication" : { "id" : 3, "name" : "name3" }}];

var newJson = {"publication" : []};

    var i = 0;
    for (var item in json) {
        var key = json[item];
        var obj = {"id" : key["publication"]["id"], "name" : key["publication"]["name"]};
        newJson["publication"][i] = obj;
        i++;
    }

If you want to format the output nicely, you can refer to this guide:

How can I pretty-print JSON using JavaScript?

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

NPM Package Encountering Module Parsing Issue

I encountered a strange error while building my project with Webpack. The error is related to the Got package that I am trying to import from its `package.json` file. Module parse failed: .../node_modules/got/package.json Unexpected token (2:8) You may ne ...

Pairing a removal request with a JSON entity

I am currently working on a project where I need to delete a specific JSON object from a JSON file once its values are displayed in a form using the AJAX Delete function. In order to achieve this, I have set up a route in Express for the JSON file as shown ...

Utilizing single-use bindings for a unique element directive

I'm working on a new directive called <call-card> and I want to implement one-time bindings as an exercise for optimizing future directives. Here is the definition object for this directive: { restrict: 'E', controllerAs: &ap ...

Adjusting the settings on my lightbox

Recently, I created a basic lightbox with the following code snippet: Here is the jQuery code: var $overlay =$('<div class="overlay"></div>'); $('body').append($overlay); $('img').click(function(){ $overlay.sho ...

Dynamically update selectable dates in Bootstrap datepicker based on availability

I've integrated WMS data into my website using Leaflet and have implemented a bootstrap datepicker that restricts date selection to a predefined array of dates by utilizing the beforeShowDay method. Now, I'm faced with the challenge of updating ...

Error: excessive recursion detected in <div ng-view="" class="ng-scope">

I've recently started learning angularJS and I've encountered an error that I need help with. Below is my index.html file: <body ng-app="myApp"> <div ng-view></div> <a href="table">click</a> <script ...

Maintain the spacing of an element when utilizing *ngFor

Using Angular.js and *ngFor to loop over an array and display the values. The goal is to preserve the spaces of elements in the array: string arr1 = [" Welcome Angular ", "Line1", "Line2", " Done "] The ...

Setting a Javascript value to a Controller variable within an ASP.NET MVC View

I am trying to set the javascript variable contentArea to match content.Contents in my controller. How can this be accomplished? <script language="javascript" type="text/javascript"> $("#btnTest").click(function () { var content ...

Removing a field from a collection using firebase-admin: Tips and tricks

I currently have a collection stored in Firebase Realtime Database structured like this: https://i.sstatic.net/jNiaO.png My requirement is to remove the first element (the one ending with Wt6J) from the database using firebase-admin. Below is the code s ...

Working with ng-model on an array with multiple dimensions

Currently, I am working on storing data in AngularJS. My table consists of various sections, rows, and columns. In each field, there is a dropdown list with the options "O", "T" or "E". My goal is to store these values in an array format: [section][row][c ...

Creating curved arcs within a polyline by utilizing the bulge feature in THREE.JS

Currently, I am importing a CAD file from a DXF format and I am looking for a way to draw an arc between two arbitrary points with a bulge value. My approach involves using THREE.Line to create segments of the arc. This resource outlines some of the essen ...

Tips for Sending Request Parameters to Angular Application

My Angular app, created with Angular CLI, is hosted on Heroku using express. The setup looks like this: const express = require('express'); const app = express(); // Serve the static files in the dist directory app.use(express.static(__dirname + ...

What is the best way to render CSS files in express.js?

My file organization looks like this: node_modules structures {HTML Files} styles {CSS Files} app.js package-lock.json package.json I have already imported the following: const express = require('express'); const app = express(); const p ...

Using Python to parse JSON messages in Spark Streaming

I am working with a Dstream consisting of JSON messages in the format {"UserID": "Xxxx", "Count": 000}. My goal is to parse it effectively in order to create a data frame. When considering this scenario, what distinguishes between option 1 and option 2: ...

Unanticipated behavior with PHP foreach loop

After receiving an array of data (POSTed from a Python application) named "observations", the structure is as follows: Array ( [0] => Array ( ['remote_id'] => 1 ['dimension_id'] => 1 ['metric&a ...

Converting a string to JSON in Golang: A step-by-step guide

I am looking for a solution to convert a string into Json format and then return it. The values received via the POST request (writePost) using c.JSON(200, string(body)) are as follows: "{\"message\":{\"@type\":\"response&b ...

XML structure is required for showing text area rows

I am looking to extract text area rows and display them in XML format. Below is the code I have tried, which successfully alerts the XML structure. The goal is to display all rows in XML format. Here is the code snippet: $(document).ready(function(){ ...

Prevent Jackson from accessing partial embedded JSON data

Within my application, I am utilizing Netty alongside a Multicast socket to receive various Multicast packets. The process involves wrapping and dividing up large data, resembling the structure below (excerpt from a class): class Packet { private long i ...

Unable to access class instance from event handler in Angular 2 and Typescript

In the scenario I'm working on, I need to dynamically add multiple instances of a child component to a template. Each of these child components emits a 'select' event, and each one requires a different event handler within the parent compone ...

In a responsive design, rearrange a 3-column layout so that the 3rd column is shifted onto or above the

My question is concise and to the point. Despite searching online, I have not been able to find any information on this topic. Currently, my layout consists of 3 columns: ---------------------------- |left|the-main-column|right| ------------------------- ...