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

Nuxt 3.11 - Best Practices for Integrating the `github/relative-time-element` Dependency

I'm encountering some difficulties while attempting to integrate github/relative-time-element with Nuxt 3.11.2 and Nitro 2.9.6. This is my current progress: I added the library through the command: $ npm install @github/time-elements. I adjusted nux ...

Unable to locate a contact within the state

Currently, I am diving into the world of React by exploring its documentation and challenging myself to build a small chat application. While I have a good grasp on the basics, I am encountering some issues with states. Within my code, there is an object ...

NodeJS: Issue when implementing try/catch with async/await causing SyntaxError

As a newcomer to Node Js, I am struggling to understand why the code below is throwing a syntax error with catch(). I recently updated to Node JS V14. Any assistance would be greatly appreciated. async function demoPromise() { try { let message ...

The value entered is displaying as not defined

As a newcomer to the world of javascript, I am diving into creating a simple To Do list. The basic functionality is there, but I'm scratching my head trying to figure out why the input value in my code keeps returning undefined. The remove button is ...

The Lenis smooth scrolling feature (GSAP) is not functioning properly

I have encountered an issue with the smooth scrolling feature of gsap causing a delay on my website. This problem is only resolved when I manually go into the browser settings and disable smooth scrolling by navigating to chrome://flags/#smooth-scrolling ...

What causes the inconsistency in TypeScript's structure typing?

It is well-known that TypeScript applies structure typing, as demonstrated in the following example: interface Vector { x: number; y: number; } interface NamedVector { x: number; y: number; name: string; } function calculateLength(v: Vecto ...

Combining two numbers retrieved from Firebase using React

Hello, I am new to React and finding it challenging to perform mathematical calculations with React. I have been attempting to add two values retrieved from a Firebase database, but they keep displaying as strings without adding the actual values together. ...

There are multiple sets of radio buttons within nested ng-repeats, but only the final group displays the selected value

I am having an issue with updating a form that contains multiple radio buttons based on data retrieved from an API. The challenge is that only the last set of radio buttons displays the value correctly. Below is the code snippet I am using (angular bracket ...

Associating checkbox options with an array that is void of elements

I have a series of arrays linked to checkboxes and I am trying to create a unique array based on the selected checkbox values. Here is an example of the HTML structure: <input type="checkbox" value="value1">Value 1 <input type="checkbox" value=" ...

Eliminate duplicated partial objects within a nested array of objects in TypeScript/JavaScript

I'm dealing with a nested array of objects structured like this: const nestedArray = [ [{ id: 1 }, { id: 2 }, { id: 3 }], [{ id: 1 }, { id: 2 }], [{ id: 4 }, { id: 5 }, { id: 6 }], ] In the case where objects with id 1 and 2 are already grou ...

Transform every character into its corresponding ASCII value within the JSON object

I need help finding a way to convert all characters in a JSON object to HTML safe characters, possibly using the htmlspecialchars() function. Instead of looping through and creating a new JSON object with character changes, I'm wondering if there is ...

Having difficulty retrieving model values from the angular ui modal dialog

Being only on my second day in the world of Angular, I am trying to navigate around Angular UI and build my first modal dialog. The modal dialog displays properly, but I'm encountering an issue with using models within it. You can view my demo on Plun ...

The Django template is unable to retrieve the JSON Key when it is enclosed in double quotes like this: {" 'Key' ": " Value "}

My Django application is communicating with an API and presenting the results in the templates. The API response includes some standard Key Value pairs and some custom fields that have a Key enclosed in both double and single quotations. The key appears ...

How to programmatically close a colorbox using an ASP.NET form's Submit button within an iframe

I've looked at other similar questions, but I just can't seem to make this work. I want to close the colorbox iframe when a .NET Button form within the iframe is clicked. <script type="text/javascript"> $(document).ready(function() { ...

Error encountered with the OffsetWidth in the Jq.carousel program

I am encountering an issue that I cannot seem to figure out. Unexpected error: Cannot read property 'offsetWidth' of undefined To view the code in question, click on this link - http://jsfiddle.net/2EFsd/1/ var $carousel = $(' #carouse& ...

Why isn't my JSON data being transmitted accurately from the front end to the back end?

Below is the JSON data that I am working with: { "fields":[ {"name":"thom","techname":"rgom","description":"dfgkjd","type":"text"}, {"name":"thom","techname":"rgom2","description":"dfgkjd","type":"text"} ] } Upon posting this JSON to a NodeJ ...

AWS Amplify-hosted Nuxt applications are resilient to errors during the build process

My website is built using Nuxt js and hosted on AWS Amplify. I've encountered a major issue where the website still gets generated successfully even when there's a failure in the nuxt generate command (like a JavaScript error in my code). Below i ...

When using Vue.js and Quasar to implement multiple filtering forms, an issue arises where the input value disappears

I am currently exploring how to implement multi-item filtering in Quasar, a framework of Vue. At the moment, I am utilizing input and checkbox elements. Everything seems to be functioning correctly, but there is an issue with the select item disappearing. ...

The process of implementing web-based online diagramming software involves a strategic approach to designing and integrating various

I'm really interested in learning how web-based online diagramming software works. If anyone could provide guidance or point me to example resources, I would greatly appreciate it. Here are some of the web-based online tools that I have been explorin ...

Switching between vertical and horizontal div layouts while reorganizing text fields within the top div

function toggleDivs() { var container = document.querySelector(".container"); var top = document.querySelector(".top"); var bottom = document.querySelector(".bottom"); if (container.style.flexDirection === "column") { container.style.flexDirec ...