Organizing dynamic JSON keys with the help of map and reduce functions in JavaScript

Is there a way to group Dynamic Object keys of a JSON file? I want the object values for each key to be grouped accordingly.

I attempted to use map and reduce functions to achieve this grouping, but the results did not turn out as I had expected.

Below is an example of my JSON Object:

var data = [ 
  {
    // JSON objects here...
  }
]

Here is the code snippet that I tried but didn't produce the desired outcome:

var x = data.map((e) => { 
  var el = {} 
    el[e.data.error.cause.root.Extracted.Body.Error.ErrorString] = 
    [e.data.error.cause.root.Extracted.Body.Error.info]; 

    return el; 
}) 

console.log(x); 

The result I obtained was:

[ 
   { 
     "NotFound": {....} 
   }, 
   { 
     // More results like above...
   } 
]

What I was expecting instead was:

[ 
 { 
   "NotFound": [ 
     { 
       // Nested objects under "NotFound" key 
     }, 
     { 
       // Another nested object under "NotFound" key 
     } 
   ] 
 },  
 { 
   // Other keys and their respective nested objects 
 } 
]

Answer №1

To condense the array, create an accumulation object with unique keys based on ErrorString. Then, populate this object with info objects corresponding to each ErrorString. Use Object.values() to retrieve the grouped values as an array.

const data=[{type:6,data:{error:{cause:{root:{Extracted:{Body:{Error:{ErrorCode:"143",ErrorString:"NotFound",info:{Error:{errorDesc:"Data Not Found",subs:{attrib:{subs_name:"123com",subs_no:4}}}}}}}}}}},status:true},{type:6,data:{error:{cause:{root:{Extracted:{Body:{Error:{ErrorCode:"143",ErrorString:"NotFound",info:{Error:{errorDesc:"Company Not Found",subs:{attrib:{subs_name:"QRS",subs_no:4}}}}}}}}}}},status:true},{type:6,data:{error:{cause:{root:{Extracted:{Body:{Error:{ErrorCode:"123",ErrorString:"SystemFailure",info:{Error:{errorDesc:"Internal server error",subs:{attrib:{subs_name:"ABC",subs_no:2}}}}}}}}}}},status:true},{type:6,data:{error:{cause:{root:{Extracted:{Body:{Error:{ErrorCode:"123",ErrorString:"SystemFailure",info:{Error:{errorDesc:"Insufficient Data",subs:{attrib:{subs_name:"DEF",subs_no:3}}}}}}}}}}},status:true},{type:6,data:{error:{cause:{root:{Extracted:{Body:{Error:{ErrorCode:"999",ErrorString:"Unknown",info:{Unknown:{desc:"UnknownError",subs:"GHI"}}}}}}}}},status:true}];

const merged = data.reduce((acc, o) => {
  const e = o.data.error.cause.root.Extracted.Body.Error;
  acc[e.ErrorString] = acc[e.ErrorString] || { [e.ErrorString]: [] };
  acc[e.ErrorString][e.ErrorString].push(e.info)
  return acc;
}, {})

const output = Object.values(merged);

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

Implement a mechanism for updating a child property whenever the parent state changes

In my setup, there's a parent state that includes a 'Theme' state. Current layout looks like this: The Parent Component holds the state of Theme. The Parent component passes down the current state to the child component as a "theme" prop ...

The functionality of images and links is compromised when they are assigned as values to properties within a JSON object

My images and links are not working, even after declaring them globally. When I write the src directly into src, everything seems fine but the alert pops up with the same URL and img src. Can anyone help? var combo0; var combo1; var combo2; var combo3; ...

A guide on adding up all the values in a table's columns with JavaScript

I have implemented a web application feature where table rows are dynamically added using JavaScript. Each row contains a Qty Col, Unit Amount Col, and Line Total Col. Users can also remove a line after adding it to the table. In this scenario, I need t ...

What is the most effective approach for handling JSON data from URLs in a professional manner?

Hey there, I'm facing a dilemma on how to efficiently handle data retrieved from various URLs on my website. My website allows me to fetch JSON data from multiple URLs. For instance, there's a page full of posts related to a specific group with ...

What is the best way to replace "NaN" with a blank space within an array?

How can I replace "NaN" with a space in an array? let numbers = [1, 2, 3, NaN]; let result = numbers.map(num => isNaN(num) ? " " : num); console.log(result); I would like the output to be [1, 2, 3, " "] ...

Choosing one item from an array to showcase in a view [Angular]

I've previously inquired about this issue without success. My current challenge involves a store app created with AngularJS. I am trying to implement a feature where clicking on an item will open it in a separate "item" view, displaying only the info ...

Using React JS to display components on a webpage

Just starting out with React. Can you assist me in displaying this section: { incidents.forEach(incident => { incident.map(inc =>{ return ( <div key={inc.id} className='inc'> <div className='incD ...

Utilize Ionic and Angular to display the local storage value within a text box

I am in the process of developing an application using the Ionic framework. I am able to upload files to the server and receive a response, which I then save the file name in localstorage. However, I am facing an issue where I need to display this value in ...

Creating an Android app using PHP, HTML, and Javascript: A step-by-step guide

I successfully developed a web application using PHP, HTML, and Javascript. My next goal is to transform it into an Android app. Can someone guide me on the process of converting a web application into an Android app? What specific tools will I need for ...

While running tests on a React project, the `npm test` command is successful, but unfortunately,

I created a new react app using create-react-app and included some basic components and tests. The tests work fine when running 'npm test', but I encounter an 'Unexpected token' error when using Jest to run the tests with imported compo ...

XSLT issue with Internet Explorer 11 - unable to transform XML file

Attempting to display an XSLT stylesheet that is retrieved from an API. It seems to be rendering correctly on Chrome and Firefox, but not on Internet Explorer. I have tried using the example provided by W3C, which works perfectly fine, but it fetches the ...

Is there a way to transform a Map<Integer, Object> into JSON using GSON?

Hey there, I'm wondering if it's possible to convert a Map to JSON and back again using GSON. The object I'm working with has already been converted from JSON to an Object using GSON. The structure of the object I'm using is as follow ...

Deactivate PyV8's automatic garbage collection functionality

I am currently experiencing an issue that appears to be stemming from the interaction between Python and PyV8's garbage collection processes. To temporarily address this problem, I have disabled Python's garbage collection and implemented a worka ...

What is the best way to organize this array containing hash elements?

Similar Question: How can I sort an array of javascript objects? The data output I'm dealing with is structured like this: [ { value: 1, count: 1 }, { value: 2, count: 2 } ] My goal is to loop through the hashes in the array and return the valu ...

Having trouble with Simplemodal showing link content in the modal window

Having trouble getting the modal window to display content from another link? I'm pretty sure I've connected them correctly using the right classes. This is the basic JavaScript provided by . jQuery(function ($) { // Load dialog on page load //$ ...

"Encountering a hiccup with Axios while making a GET request in a React

I've been attempting to retrieve data from the API using an axios get request, but I keep encountering an error. The error message reads as TypeError: this.setstate is not a function. Despite looking at various solutions for similar issues, most of th ...

Error: The function $.get is not recognized when using jQuery with babel-node

Currently, I am executing the code below from a test.js file using babel-node in the command line: babel-node test.js installation of jquery npm i --save jquery test.js: import $ from 'jquery'; $.get("www.google.com"); Upon execution, I en ...

Centered on the screen are the input field and corresponding label

I am in the process of creating a signup form, and I have encountered an issue. How can I make the input wider without using a fixed width like width: 420px? Additionally, I would like to center both the input field and the label. I envision something simi ...

Tips for preventing route changes when clicking on a hash tag in AngularJS

I have a link in a small carousel on the page, and I am utilizing AngularJS routing to create a Single Page App. The tiny carousel uses anchor tags as buttons to navigate between images. <div class="carousel-controls-mini"> <a href=" ...

Unable to locate module - relative file path

I'm currently running a test with the following code and encountering an error message: Failed: cannot find module '../page/home_page.js The main page consists of: describe("login to website",function(){ var employeeId; var employee ...