working with JSON array information

I have a JSON array retrieved from a database that I need to manipulate. Currently, it consists of 8 separate elements and I would like to condense it down to just 2 elements while nesting the rest. The current structure of my JSON looks like this:

{
  "itemId": 1,
  "desc": [{
    "type": "A",
    "size": "xx",
    "count": 12,
    "price": 122
  },
  {
    "type": "A",
    "size": "xl",
    "count": 18,
    "price": 180
  },
  {
    "type": "B",
    "size": "xx",
    "count": 12,
    "price": 122
  },
  {
    "type": "B",
    "size": "xl",
    "count": 12,
    "price": 122
  }]
}

The data needs to be transformed into the following format:

{
 "type": "A",
  "desc":{
    "size": "xx",
    "count": 12,
    "price": 122
  },
  {
    "size": "xl",
    "count": 12,
    "price": 122
  },
 },
  {
 "type": "B",
  "desc":{
    "size": "xx",
    "count": 12,
    "price": 122
  },
  {
    "size": "xl",
    "count": 12,
    "price": 122
  },
 }

Although I am currently using a forEach loop to achieve this, it is producing individual elements instead of the desired two elements in the resulting array. Any solutions or suggestions would be greatly appreciated.

Answer №1

One way to approach this is by using the following code:

var newData = {
    A: {type: 'A', desc: []},
    B: {type: 'B', desc: []}
};

$.each(data.desc, function( index, value ) {
  newData[value.type].desc.push(value);
});

You can also handle unknown types dynamically with the following code:

var newData = {};

$.each(data.desc, function( index, value ) {
  if(typeof newData[value.type] === "undefined") {
    newData[value.type] = {type: value.type, desc: [value]}
  } else {
    newData[value.type].desc.push(value);
  }
});

For a working example, you can visit https://jsfiddle.net/5cnaxn04/1/

Answer №2

Your code contains multiple syntax errors, particularly with the use of {} for both Arrays and Objects. It seems like you may need to incorporate some loops in order to format the data correctly according to your desired output.

For a demonstration, refer to this JSFiddle link.

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

Encountering issues with IEnumerable in a view that contains a JSON object

After successfully serializing a JSON string in a previous question, I have encountered difficulty displaying the results on the view. Despite fixing the model and controller, it seems that the issue lies within the view itself. The error message I am curr ...

Obtain the identification number and full name from the typeahead feature

I am able to retrieve the name and ID, but I am only able to display the name. I have attempted using update and afterslected methods. Currently, I have this code which works well, however, it only fetches the name! $('input.typeahead').typea ...

Analyzing intricate JSON data as a data frame in R

Here is the JSON data that I have: json_data <- data.frame(changedContent=c('{"documents":[],"images":[],"profileCommunications":[],"shortListedProfiles":[],"matrimonyUser":{"createdBy":null,"parentMatrimonyUserId":0,"userSalutationVal":"Mr.","mat ...

Exploring how to handle JSON data transmitted through websockets using JQuery

I am currently attempting to transmit data to the client using a JSON object and a websocket connection. The JSON object has been successfully sent as validated by a JSON web application. Upon receiving, here is the jQuery client-side code: $(document). ...

Adding roles in ReactJS: A step-by-step guide

I am looking to enhance the admin's roles upon login to enable the creation of new users. Unfortunately, I am uncertain on how to add these roles and make them functional. Below is the code I have: Login.js class Login extends Component { cons ...

Issue: [unresolved] Provider not recognized: $resourseProvider <- $resourse <- Phone Angular factory

I'm encountering an issue with injecting a resource. Error: [$injector:unpr] Unknown provider: $resourseProvider <- $resourse <- Phone Here is my code: index.html <script src="bower_components/angular/angular.js"></script> < ...

Guide to establishing multiple relationships using the `belongsTo` method within a Loopback model

In my database, I have three models named "Companies," "Employees," and "Employments." The "Employments" model is set up to have a belongsTo relationship with both a company and an employee. Inversely, every "Employee" should have a hasOne relationship wit ...

Steps for displaying the JSON data from Google Distance Matrix Results in a printed format

How can I display the results from Google Distance matrix? Here is the format of the results: "rows" : [ { "elements" : [ { "distance" : { "text" : "4,8 km", "value" : 4820 }, "du ...

Triggering on multiple clicks - MULTIPLE CLICKS

I'm currently in the process of developing a website and I have a specific requirement where I need an image to change on click to another image, and then to a third image on the second click, and so forth. I've managed to create a JavaScript fu ...

Extract portions of the date into individual variables

My current project involves creating a front-end interface for data stored in a JSON database. The date information is saved in the following format: 12/31/16 I am trying to extract each of these values individually. Is there a method to assign variabl ...

What is the best way to notify a user one minute before their cookie expires using PHP and JavaScript?

I need a solution to alert my logged-in users one minute before their cookie expires, allowing them to save content in the CMS. Any ideas on how I can make this happen? In my auth file, I have configured the following: setcookie("USERNAME", $user,time()+ ...

using selenium to interact with elements within the window object

I'm a newcomer to selenium and javascript and looking to incorporate the VisualEvent javascript into pages opened in a selenium-controlled browser. My goal is to access its variables from selenium in java. I've successfully completed the first ph ...

What is the correct way to parse a JSON array of arrays using the Jackson JSON parser?

I have an API that generates the following JSON: { "monitors": [ [ "/Common/http-cc-ping-any" ] ], "is_alive":true } I am attempting to utilize Spring and Jackson JSON Parser to map this JSON to a POJO. The POJO i ...

Vue Mutation IndexOf returns a value of -1

Hey everyone! I'm facing a challenge with deleting a "product." Although the product is successfully removed from the database, I'm encountering an issue with removing it from the VuexStore array of products. Here's what I've tried so f ...

Tips for sending arguments up in Angular2

I need to supply an argument to a function. <select class="chooseWatchlist" (change)="updateWatchlistTable(item.name)"> <option *ngFor="let item of _items">{{ item.name }}</option> </select> It's crucial for me, as I have ...

Regular expressions - For alphanumeric or numeric with a possible slash character included

I need assistance with extracting alphanumeric values from a string array using RegEx. For instance: Apartment 101/B First Villa 3324/A Second Milk 12MG/ML Third Sodium 0.00205MG/ML Fourth Water 0.00205MG Fifth Eggs 100 Sixth My goal is to retrieve the v ...

Passing the title of a page as data to a component in Next.js

I am currently working on setting a custom title for each page within my next.js project. Here is an example of a simple Layout: const MainLayout = props => { return ( <Layout style={{ minHeight: "100vh" }}> <Head> < ...

Categorize the Laravel collection by the specified key

Is there a way in Laravel to modify the response when the same user has multiple responses in an array? The current response function in the controller is as follows: controller.php public function index(){ $reports = Report::all(); return $this- ...

How can the syntax of a JSON file be verified in Unix?

How can I verify the syntax of a JSON file in Unix and then automatically move any invalid files into an error folder? Thank you, Kavin ...

Having trouble importing a module or library in VueJS?

After setting up a slider library called Hooper in VueJS 3, I imported it locally like this: <template> <hooper> <slide>1</slide> <slide>1</slide> <slide>1</slide> <slide>1</slide&g ...