Formatting JSON with two fields

I attempted to organize JSON data based on city names using this fiddle code.

Now, I am trying to group the data by city name and city code. Any suggestions or hints regarding the logic would be greatly appreciated.

CurrentDataFormat = [{
        "Id": 17,
        "code": "123",
        "cityName": "Los Angeles",
        "cityCode": "LA",
        "startDate": "1/20/2016",
        "endDate": "1/20/2016"
    },

    {
        "Id": 18,
        "code": "456",
        "cityName": "Chicago",
        "cityCode": "CH",
        "startDate": "1/22/2016",
        "endDate": "1/25/2016"
    },

    {
        "Id": 19,
        "code": "789",
        "cityName": "Los Angeles",
        "cityCode": "LA",
        "startDate": "1/13/2016",
        "endDate": "1/21/2016"
    }
]

GroupByJsonFormatData(CurrentDataFormat);

function GroupByJsonFormatData(CurrentDataFormat)
{
var refinedArray = {};

for (i = 0; i < CurrentDataFormat.length; i++) {
    refinedArray[CurrentDataFormat[i].cityName] = refinedArray[CurrentDataFormat[i].cityName] ? refinedArray[CurrentDataFormat[i].cityName] : {};

    refinedArray[CurrentDataFormat[i].cityName].name = CurrentDataFormat[i].cityName;

    refinedArray[CurrentDataFormat[i].cityName].CityData = refinedArray[CurrentDataFormat[i].cityName].CityData ? refinedArray[CurrentDataFormat[i].cityName].CityData : [];
    refinedArray[CurrentDataFormat[i].cityName].CityData.push({
        "Id": CurrentDataFormat[i].Id,
        "code": CurrentDataFormat[i].code,
        "startDate": CurrentDataFormat[i].startDate,
        "endDate": CurrentDataFormat[i].endDate
    });
}

var ExpectedDataFormat = [];

for (singleCityName in refinedArray){
    ExpectedDataFormat.push({'name' : refinedArray[singleCityName].name, 'CityData' : refinedArray[singleCityName].CityData});
};

console.log(ExpectedDataFormat);
document.getElementById("resultPane").innerHTML = JSON.stringify(ExpectedDataFormat, undefined, 2);;
}

I also tried to make this code more dynamic by passing column names as parameters. For instance, attempting something like GroupByJsonFormatData(CurrentDataFormat, GroupByColumn); and trying to concatenate this parameter with array like

refinedArray[CurrentDataFormat[i].+GroupByColumn]

but unfortunately, it did not work at the concatenation level.

Answer №1

To streamline your code, consider the following techniques:

refinedArray[CurrentDataFormat[i].cityName] = refinedArray[CurrentDataFormat[i].cityName] || {};

Rather than using

refinedArray[CurrentDataFormat[i].cityName] = refinedArray[CurrentDataFormat[i].cityName] ? refinedArray[CurrentDataFormat[i].cityName] : {};

A similar approach can be taken with arrays:

refinedArray[CurrentDataFormat[i].cityName].CityData = refinedArray[CurrentDataFormat[i].cityName].CityData || [];

For a more versatile solution, you can utilize

refinedArray[CurrentDataFormat[i]][GroupByColumn]

Answer №2

Utilizing Lodash can provide a solution:

var groupedByCity =  _.groupBy(DataFormat, "cityName")

You may be interested in modifying the keys or exploring other functionalities together.

Check out this helpful suggestion or refer to the documentation for more information.

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

Moving the starting directory of a NodeJS application on Azure

My NodeJS app on Azure was initially written in Javascript with the app.js file located in the root directory. This file was automatically detected during deployment via Git. Recently, I converted the app to Typescript and now have a build directory, with ...

What could be causing the property of the object to be inaccessible in a ternary equation, yet functional in JSX in React?

I have an object that resembles the structure below: campground { "uri": "/campgrounds/long-island-bridge-campground-llc/", "acfDetails": { "picture": { "mediaItemUrl": "/uploads/2021/04/ ...

Leveraging Spring to send multiple JSON requests (POST) in a single HTTP request

Looking to leverage the Spring3 framework for combining two different REST requests using JSON within a single HTTP call? Utilizing Spring with jackson for JSON conversion, what would be the most efficient approach for this task? Unclear whether this falls ...

Experiencing a hiccup in React while attempting to play an mp3 file

My project includes the following code snippet, with an example mp3 file and npm package: https://www.npmjs.com/package/react-sound import React from 'react'; import Sound from 'react-sound'; class CustomSound extends React.Component ...

Steps for combining two collections into a single output in MongoDB with Node.js

My MongoDB collections consist of data that I need to merge using the $lookup operation. However, the result I get contains a nested array structure that is not ideal. I am looking for a solution to format the result as shown below: First collection locati ...

What causes CSS animations to suddenly halt?

Recently, I've been delving into the world of CSS animations and experimenting with some examples. Below is a snippet of code where two event handlers are set up for elements, both manipulating the animation property of the same element. Initially, th ...

Just starting out with JavaScript - updating the appearance of an element

Based on the value of a boolean, I am looking to control the visibility of specific tabs in my sidebar when the page loads. var someVar = true; function show_ifTrue() { if (Boolean(someVar) == true) { document.getElementById('x'). ...

Generating JSON array objects dynamically in JavaScript code

Need help with organizing my code let newArr = []; $.post( "/reports/search", { query:'*'},function(data) { for(let i=0; i<data.length; i++) { newArr[i].value = data[i].name; newArr[i].data = data[i].id; } },'json ...

Change PHP code into a PNG file

Here are the scripts I am working with: http://pastebin.com/RuHKcAfc http://pastebin.com/f3xXdigj If you visit the live version at this link: , you will see that the json data () is displayed on a php-generated image. $imagem = new Image(502, 500, ' ...

Having trouble accessing a PDF file using gview

Having trouble opening a document I am unable to preview the documents and I'm not sure what I'm missing. I have read through various StackOverflow questions and answers related to this issue, but still no luck. url = http://192.168.0.6:8077/ ...

How to handle JSON parsing in a sails.js controller with node.js

Within my MapController, I have created a function to parse remote JSON files and populate an array called "parsewebservice" through an if-else structure. While everything seems to be working fine, the issue arises when trying to log the values of parseweb ...

As I traverse along a row and delete a cell that matches - the 'replace' method is not available

My goal is to loop through a set of td elements within a tr and remove the first one that contains a specific string (each cell holds a word and there will only be one match). The issue lies in this block of code: $('#row > td').each(function ...

Having trouble with the Twitter share count URL - seeking out other options

Previously, I utilized the following Javascript function to retrieve the Twitter share count for a URL. Unfortunately, Twitter has discontinued providing the share count. Is there a more effective alternative available? // Twitter Shares Count $.getJSON ...

Having trouble with typecasting in Angular 9 after receiving an HTTP response?

When initializing my component, it fetches student information from an API. Here is the ngOnInit code for component-version1: ngOnInit(): void { if(!this.student) { this.studentsService.getStudentDetail(this.id).subscribe( (response: Stu ...

How to retrieve element from templateUrl in AngularJS controller

I am facing a challenge in populating select(option) element inside a template html file from the controller. Although I have managed to do it successfully, I am unable to set a default value to avoid the initial empty option. Here is a snippet from the t ...

Guide on incorporating botframework into a mobile application...?

Recently, I developed a chatbot utilizing the MS bot framework in Nodejs. To display the chatbot in an HTML format without iframes, I incorporated a React Component from the link provided at https://github.com/Microsoft/BotFramework-WebChat. At this point, ...

Getting a ReferenceError while trying to use a MongoDB Collection variable in an external resolver file that had been imported through mergeResolvers

Here is a simplified example to illustrate the issue at hand. When using the resolver Query getAllUsers, the MongoDB Collection Users is not accessible in the external resolver file user.js. This results in the following error when executing the query: ...

Using jq and node.js to translate AWS EC2 tags

Seeking assistance with transforming this array of EC2 tags using jq and node.js: [ { Key: 'Name', Value: 'xxx' }, { Key: 'role', Value: 'yyy' } ] I want to transform it to: { name : 'xxx', ro ...

The element is being offset by SVG animation that incorporates transform properties

I'm working on creating a halo effect by rotating an SVG circular element using the transform rotate function. I've been using getBox to find the center point of the element, but when the rotation occurs, the overall image is getting misaligned w ...

The MUI5 drawer overlapping a modal dialog

Is it possible to use MUI5 to open a side drawer on top of a modal dialog that triggers it? Currently, the dialog triggers the side drawer but it opens behind this. It appears as though a modal dialog (drawer) is attempting to open over an already-opened ...