Extract distinct data from JSON object

Here is a JSON object that needs to be parsed:

var data =JSON.parse('[{"Title":"Test 1","State":"Colorado"}, 
                       {"Title":"Test 1","State":"Arizona"},
                       {"Title":"Test 2","State":"Utah"},
                       {"Title":"Test 2","State":"Arizona"},
                       {"Title":"Test 3","State":"Arizona"}]');

The desired output after parsing the data object should be as follows:

resultData = [{"Title":"Test 1", State: ["Colorado", "Arizona"]},
              {"Title":"Test 2", State: ["Utah", "Arizona"]},
              {"Title":"Test 3", State: ["Arizona"]}]

There has been an attempt made with the following code:

var resultData = {},
groupBy = "Title";

for (var i = 0; i < data.length; i++) {
    if (!resultData[data[i][groupBy]])
        resultData[data[groupBy]] = [];
    resultData[data[i][groupBy]].push(data[i]);
};

However, the current output is not as expected:

resultData = [{Test 1: [{State: "Colorado"}, {State: "Arizona"}]},
              {Test 2: [{State: "Utah"}, {State: "Arizona"}]},
              {Test 3: [{State: "Arizona"}]}]

If anyone can provide assistance in achieving the desired output, it would be greatly appreciated.

Answer №1

Your goal can be efficiently achieved using the reduce method:

Step 1 - Parsing Data

var data = JSON.parse('[{"Title":"Test 1","State":"Colorado"}, 
                       {"Title":"Test 1","State":"Arizona"},
                       {"Title":"Test 2","State":"Utah"},
                       {"Title":"Test 2","State":"Arizona"},
                       {"Title":"Test 3","State":"Arizona"}]');

Step 2 - Combining States with Same Title

var titles = data.reduce(function(acc, item){
    var title = item.Title;
    var state = item.State;

    if (!Object.prototype.hasOwnProperty.call(acc, title)){
        acc[title] = [];
    }

    acc[title].push(state);
    return acc;
}, {});

Step 3 - Building Final Array from Combined States

var resultData = Object.keys(titles).map(function(title){
    return {
        Title: title,
        State: titles[title]
    }
});

This code block demonstrates the above steps in JavaScript for achieving the desired outcome.

Answer №2

A potential solution involves utilizing a single loop strategy that incorporates a closure over a hash table for organizing the data into specific groups.

var information = [{ Name: "Test 1", Location: "Colorado" }, { Name: "Test 1", Location: "Arizona" }, { Name: "Test 2", Location: "Utah" }, { Name: "Test 2", Location: "Arizona" }, { Name: "Test 3", Location: "Arizona" }],
    key = 'Name',
    groupedInformation = information.reduce(function (group) {
        return function (result, object) {
            if (!group[object[key]]) {
                group[object[key]] = [];
                result.push({ Name: object.Name, Locations: group[object[key]] });
            }
            group[object[key]].push(object.Location);
            return result;
        };
    }(Object.create(null)), []);

console.log(groupedInformation);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Trigger an event in Angular using TypeScript when a key is pressed

Is it possible to activate a function when the user presses the / key in Angular directly from the keydown event? <div (keydown.\)="alerting()"> </div> <div (keydown.+)="alerting()"> </div> Both of these ...

My attempt at automatically submitting the form using jQuery to the ajax function was unsuccessful, and no error messages were displayed

I've been experimenting with different approaches to solve this issue for the past two hours, but haven't had any luck yet. It's frustrating :( I am currently working on creating new form elements using values generated from JSON and a jQue ...

Having trouble installing the json gem on Ubuntu using Ruby 2.2.3

I've been following a Rails tutorial but encountered an issue while trying to run 'bundle install' because of a problem with the json gem. When I tried to install it directly: me@tru2:~/rails/hello_app$ gem install json -v '1.8.3' ...

What is the method for incorporating input value into a li list item?

I am attempting to insert the content of an input as a list item (<li>) in an unordered list (<ul>). I managed to add it by connecting the value to the array list of list items. However, it disappears when I clear the input field. How can I re ...

Retrieve an object using a variable

Essentially, my question is how to extract a value from a variable and input it into a sequence. Being Dutch, I struggle to articulate this query correctly. var channelname = msg.channel.name; "description": `${config.ticketlist.channelname.ticketmessage} ...

Failure to execute Ajax request when searching for a query

My personal GitHub profile viewer React application allows you to search for a profile by username. By default, my own GitHub username is provided on the landing page. However, when trying to search for another user, my ajax call is not functioning properl ...

Creating dynamic child components in Vue.js version 2

I am currently developing a facet search system using VueJS. The concept is fairly straightforward: Within a FilterGroup component lies the overarching filter logic. This component allows for several child components, such as AttributeXYZFilter, to provid ...

Organize table information using rowspan functionality

View of Current Table I am looking to implement a side column in my table using rowspan to group dates within each pay period. The goal is for a supervisor to be able to create a new pay period, which will assign a unique integer in the database and then ...

Are you utilizing content loaded through jquery load in your work?

I have successfully utilized jQuery's .load() function to retrieve the contents of a table from another webpage and insert it into the current page, which is functioning properly. However, when I try to run scripts afterwards that manipulate the newly ...

Create a KML layer on a Google Map by uploading from a text input field

Is there a way to use the javascript api to draw a kml layer on a google map by copying the kml code from a textarea, similar to how it can be done on this page? Most examples in the documentation I found demonstrate loading the kml layer from a file. ...

Navigating through JSON data retrieved from a MySQL database or within Xcode

In my app, customers are prompted to specify the features they are looking for in a rental car. These preferences are then sent to my Database where a search is performed to determine the number of available cars that match the criteria. I am currently co ...

Tips for including HTML tags within a string using node.js, express, and ejs

Currently, I am utilizing Node.js with Express and EJS for my project. My goal is to pass HTML tags within a string to the browser in the following manner: listRequests.forEach(function(key) { messages.push("You have a message from <b>" + key.us ...

"How can you enhance the performance of JavaScript and CSS in a Chrome Extension without using exclude_matches/globs or excluding domains

I have been in the process of creating a Chrome Extension, and unfortunately, when I tried to make it work on specific URLs, I encountered an issue. While Chrome has options like exclude_matches and exclude_globs for this purpose, there seems to be a bug i ...

What are the steps for showcasing a personalized HTML tag on a web page

I need to capture user input text and display it correctly. This is what I have attempted: <div> <input type="text" ng-model="post.content" /> </div> <div> <div ng-bind-html="post.content| htmlize"></div> < ...

Getting your JS project off the ground with NPM!

I am looking to develop a vanilla JavaScript project that utilizes npm packages, but I want to do it without using bundlers like Webpack. Here is a basic structure: index.html: <div id="app"></div> <script src="./index.js" type="module"&g ...

Empty array is logged by the server after sending a JavaScript variable through post request

When I use console.log(request.body), the terminal displays {} instead of logging the variable ownerSteamId. Here is my code: Server-side JavaScript: const express = require('express'); const app = express(); const bodyParser = require('bod ...

Search a location database using the user's current coordinates

Currently, I am working on a project that involves a database containing locations specified by longitude and latitude. Upon loading the index page, my goal is to fetch the user's location and then identify every point within a certain distance radius ...

Executing a setInterval function in NodeJs without prolonging the process's lifespan

To better grasp what I need to do, I simplified the task at hand: we have a lengthy nodejs process with numerous queued async functions, making it impossible to predict when they will finish. Our goal is to create an update process that stores the current ...

Credit for the Position swipejs

After integrating a swipeJS photo slideshow into my jQuery mobile application, I encountered an issue. I am trying to create points for counting the pictures similar to what is seen on this page: Although I have added the necessary HTML and CSS code to my ...

Tips on manually refreshing AngularJS view using ControllerAs syntax?

As I work on creating a user-friendly dashboard with widgets that can be sorted, docked, and floated, I encountered an issue. The controls I am using generate floating widgets as HTML at the bottom of the DOM, outside the controller scope where they were c ...