A guide on organizing a JSON object in JavaScript/AngularJS through grouping

My JSON object contains zip code entries organized by the "Zipcode" key. My goal is to group these entries by zip code to display which zone IDs are associated with each zip code. For example, zip code 7 corresponds to zone IDs 12005, 12008, 12006, and 12009, while zip code 12 corresponds to zone IDs 12004 and 11001. The end result should be displayed in an error message.

var Json = [{
City: "ABC",
ZipCode: "7",
ZoneID: 12008,
ZoneName: "test_TP41"},
{City: "ABC",
ZipCode: "7",
ZoneID: 12005,
ZoneName: "test_TP4"
},
{City: "ABC",
ZipCode: "7",
ZoneID: 12007,
ZoneName: "test_TP456"},
{City: "ABC",
ZipCode: "7",
ZoneID: 12006,
ZoneName: "test_TP5"},
{City: "ABC",
ZipCode: "7",
ZoneID: 12009,
ZoneName: "testgrp16"},
{City: "CDE",
ZipCode: "12",
ZoneID: 12004,
ZoneName: "test_TP2"},
{City: "CDE",
ZipCode: "12",
ZoneID: 11001,
ZoneName: "test 20201"
}]

Answer №1

If you're looking to organize your data in a similar structure, try the following approach:

obj = {
  ZipCode: [all objects with this specific ZipCode],
}

Json = [{
City: "ABC",
ZipCode: "7",
ZoneID: 12008,
ZoneName: "test_TP41"},
{City: "ABC",
ZipCode: "7",
ZoneID: 12005,
ZoneName: "test_TP4"
},
{City: "ABC",
ZipCode: "7",
ZoneID: 12007,
ZoneName: "test_TP456"},
{City: "ABC",
ZipCode: "7",
ZoneID: 12006,
ZoneName: "test_TP5"},
{City: "ABC",
ZipCode: "7",
ZoneID: 12009,
ZoneName: "testgrp16"},
{City: "CDE",
ZipCode: "12",
ZoneID: 12004,
ZoneName: "test_TP2"},
{City: "CDE",
ZipCode: "12",
ZoneID: 11001,
ZoneName: "test 20201"
}]

const res = Json.reduce((acc, curr) => {
  if(acc.hasOwnProperty(curr.ZipCode)) {
    acc[curr.ZipCode].push(curr);
  } else {
    acc[curr.ZipCode] = [curr];
  }
  return acc;
}, {});

console.log(res);

To only include ZoneID values in the array, you can use the following snippets:

acc[curr.ZipCode] = [curr.ZoneID];

and

acc[curr.ZipCode].push(curr.ZoneID);

Answer №2

For additional categorization, you can refer to this particular solution.

If you're using ES5+, try the following code snippet:

var grouped = _.mapValues(_.groupBy(Json , 'ZipCode'),
                          singleObject=> singleObject.map(item=> _.omit(Json , 'ZipCode')));

console.log(grouped);

I trust that this information will prove useful to you.

Answer №3

To iterate through and generate an object with ZipCode as the key and ZoneID as the value is a common task.

const Data = [{
City: "DEF",
ZipCode: "23",
ZoneID: 12003,
ZoneName: "test_TP31"},
{City: "DEF",
ZipCode: "23",
ZoneID: 12002,
ZoneName: "test_TP3"
},
{City: "GHI",
ZipCode: "45",
ZoneID: 12001,
ZoneName: "test_TP21"},
{City: "GHI",
ZipCode: "45",
ZoneID: 10001,
ZoneName: "test_TP1"
}];

const ZipObject = {}

Data.forEach((k)=>{
if(ZipObject[k.ZipCode]){
  ZipObject[k.ZipCode].push(k.ZoneID)
} else {
ZipObject[k.ZipCode] = [k.ZoneID]
}
})
console.log(ZipObject)

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

The jQuery method .find() is unable to locate the <option> tag and behavior unpredictably

Currently, I am working on a webpage that features a table with filtering capabilities using jQuery. The filtering functionality is achieved through a Bootstrap 4 dropdown menu where each option is assigned a specific value: <select id="inputState& ...

What is the significance of including the keyword 'default' when exporting a component with withStyles?

When I create a simple React component using Mui's withStyles HOC, I find that I am required to export the component as default. Why is it not possible to use the HOC directly in the return statement of the functional component? Is there something sp ...

What is the best way to extract the created_time field from this Instagram JSON object?

After receiving this JSON data, I noticed that the created_time value displays the time in integer format instead of a proper time format. How can I convert the created_time into the correct format? "filter"=>"Normal", "created_time"=>"1421677966" ...

Enhanced JavaScript Regex for date and time matching with specific keywords, focusing on identifying days with missing first digit

I have a specific regular expression that I am using: https://regex101.com/r/fBq3Es/1 (audiência|sessão virtual)(?:.(?!audiência|sessão virtual|até))*([1-2][0-9]|3[0-1]|0?[1-9])\s*de\s*([^\s]+)\s*de\s*((19|20)?\d\d) ...

Performing two ajax calls within a non-existent div that has only just been appended

I've been developing a website similar to 9gag. I attempted to incorporate a voting feature created by someone else, as I'm not well-versed in AJAX requests, but it just doesn't seem to be functioning. My index.php file fetches five posts f ...

Removing a Row from an HTML Table with JavaScript

I am currently facing an issue with my JavaScript code that is intended to delete a row from an HTML table. Additionally, I have a JavaScript code snippet that generates a column dynamically at runtime with a delete anchor tag. var tbody = document.getEl ...

The multi-level navigation bar is not displaying properly

I am currently facing an issue with my Mega menu. It displays two levels of menus perfectly fine, but I need to add a third level as shown in the image below. However, when I try to include the third level, it disrupts the design and causes the Grand Child ...

Is there a way to stop myself from accidentally clicking twice on the same tile?

I'm currently working on a game and facing an issue where my "X" gets deleted when clicking twice on the same tile. I am able to move my "X" around, but the double-click deletion is causing trouble. I attempted using booleans but struggle with them. I ...

Is there a way to detect and capture the enter key press in Firefox 3.5 in order to redirect the page using the Window.Location

I've been working on implementing a search feature in an ASP.NET 3.5 application that captures the enter key and redirects to a different page. It's been working flawlessly in Internet Explorer, but unfortunately, I've run into an issue with ...

What are the steps to connect Google Calendar?

I am facing a challenge in integrating Google Calendar with DialogFlow and I could use some help. In the Fulfillment section of my project, I have inserted the following code. However, I keep encountering Firebase errors: TypeError: Cannot read proper ...

Utilize Angular Js to play a hidden sound in the background without any visible controls

Is there a method to incorporate a background sound without visible controls using Angular JS? I am currently working on an app using Cordova Visual Studio tools. ...

Finding and comparing a specific portion of a text in JavaScript: A guide

Can you help me with a JavaScript algorithm that can find a substring within a string? subStringFinder('abbcdabbbbbck', 'ab') This should return index 0. Similarly, subStringFinder('abbcdabbbbbck', 'bck') should ...

Maximizing the Potential of AngularJS with HTML Injections via Chrome Extensions

Is there anyone out there who has experience using AngularJS for Chrome extensions? If I wanted to insert a div into a page and have control over the layout and structure, what would be the best approach? I'm concerned about interfering with the par ...

"Receiving EOF error while attempting to send JSON data to local Go backend with VueJS

I'm currently in the process of establishing a login system with VueJS for the frontend and Go for the backend. However, I've hit a roadblock when it comes to sending the username and password in JSON format to the backend. My current approach i ...

Sorting arrays in ES5 with the sort() method

In my array, I have multiple objects with a 'time' property that stores date strings. elements = [ {time: "2013-03-01T10:46:11Z"}, {time: "2013-03-03T10:46:11Z"}, {time: "2013-03-02T10:46:11Z"} ] My goal is to ...

A step-by-step guide on incorporating a JSON array into a JSON file using Python

There is an array that looks like this: [{"Name": "abcd"}, {"Name": "efgh"}, {"Name": "hijk"}] The task at hand is to add this array to a JSON document. The JSON document in question resembles the following: {"widget": { "debug": "on", ...

Error occurs during server to server mutation with Apollo Client (query successful)

Currently, I am using apollo-client on my web server to interact with my graphql server (which is also apollo). While I have successfully implemented a query that retrieves data correctly, I encounter new ApolloError messages when attempting a mutation. Od ...

Changing element visibility based on AJAX interactions

As a novice, I am struggling to modify this code. This particular example fetches a stock quote (including the day's low and high) from a PHP file using Ajax. The result is then embedded in the page itself, with an animated GIF indicating progress. ...

In TypeScript, there is a curious phenomenon where private properties seem to be mimicking the

Here is an example of an issue I encountered while working with private properties in TypeScript. I expected that only the public properties would be visible in my object output, similar to normal encapsulation. My aim here is to include the property wit ...

Gulp's synchronous tasks encounter issues when running properly in the AngularJs environment

I'm currently diving into Gulp to streamline my workflow, specifically focusing on setting up an AngularJS environment using Gulp for minifying and concatenating files. However, I've run into a roadblock where Gulp seems unable to find the config ...