Organizing objects by their unique key in JavaScript

Help needed with grouping JavaScript objects by age. Below is my JSON data:

var jsonObj=[{"name":"john","age":23},{"name":"mark","age":25},{"name":"jeni","age":21}]`

I am looking for a grouped result similar to this format.

[23:{"name":"john","age":23},25:{"name":"mark","age":25},21:{"name":"jeni","age":21}]

I have attempted using map and filter, but unable to achieve the desired output. Any assistance would be greatly appreciated.

Answer №1

Utilize the power of Array#reduce to group objects based on a specific property, such as age. If there are multiple individuals with the same age, gather them into an array under that age:

var jsonObj=[{"name":"john","age":23},{"name":"mark","age":25},{"name":"poll","age":23},{"name":"jeni","age":21}];

var result = jsonObj.reduce(function(r, o) {
  r[o.age] || (r[o.age] = []); // create an array for each unique age
  
  r[o.age].push(o); // push the object into the respective age's array

  return r;
}, {});

console.log(result);

Alternatively, you can use the concise ES6 one-liner version:

var jsonObj=[{"name":"john","age":23},{"name":"mark","age":25},{"name":"poll","age":23},{"name":"jeni","age":21}];

var result = jsonObj.reduce((r, o) => ((r[o.age] || (r[o.age] = [])).push(o), r), {});

console.log(result);

Answer №2

To obtain the hash table as output, iterate through the data and generate new arrays for each unique key. Finally, add the object to the resulting hash table.

var data = [{ name: "john", age: 23 }, { name: "mark", age: 25 }, { name: "poll", age: 23 }, { name: "jeni", age: 21 }],
    result = {};

data.forEach(o => (result[o.age] = result[o.age] || []).push(o));

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

Answer №3

If you're looking for a solution, consider using underscore js. Ensure to include underscore js in your project first by adding the following script:

<script src='https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js' ></script>

Once included, you can easily obtain the desired result with the code snippet below.

var result=_.indexBy(jsonObj, 'age');

Answer №4

Here's a sample code snippet to group objects by age:

const people = [{ "name": "john", "age": 23 }, { "name": "mark", "age": 25 }, { "name": "poll", "age": 23 }, { "name": "jeni", "age": 21 }];
let groupedByAge = {};
people.forEach(person => {
    if(groupedByAge.hasOwnProperty(person.age)) {
        if(Array.isArray(groupedByAge[person.age])) {
            groupedByAge[person.age].push(person);
        } else {
            groupedByAge[person.age] = [groupedByAge[person.age], person];
        }
    } else {
        groupedByAge[person.age] = person;
    }
});
console.log(groupedByAge)

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

Discovering the appropriate use cases for BeanSerializer and MapSerializer is a skill that Jackson must learn

I have a bean that returns a Map as a response, and this bean is accessed through a REST interface using RESTEasy. Instead of using MapSerializer, the jackson library internally uses BeanSerializer to send the response back. Is there any annotation being ...

Prevent modal from closing when tapping outside of it

I'm currently facing a challenge in creating a popup modal that cannot be closed by clicking outside the modal window. I have explored various solutions involving backdrops but none of them seem to be effective. Any assistance would be greatly appreci ...

Best way to create a 3D array in PHP

I am trying to structure an array in PHP that resembles the following format: _________________________________________ |time | event | childEvents | |_____|_______|__________________________| |9:00 |Event1 | String[]{subE11, subE12} | |_____ ...

Most effective method for sending information from an HTTP server to a browser client

What is the most effective method for transferring data from the server side to the client when the client is a web browser? The server side is developed in Java, while the client side uses HTML, JavaScript, and AJAX. The communication protocol being uti ...

Having trouble importing zone.js in Angular 14 and Jest 28

I am currently in the process of updating to Angular 14. Everything is going smoothly except for setting up jest. Since I have Angular 14 libraries included in my build, I need to utilize jest-ESM support. Below is my configuration: package.json { &qu ...

Switch the functionality of a Google Chrome extension back and forth numerous times

My Google Chrome extension works by attaching event listeners to all elements on a page and inserting CSS (lol.js and style.css) when clicked. However, I am facing an issue where I cannot remove the JS and CSS upon clicking the icon again. Right now, I am ...

Using jQuery to iterate through elements of a PHP array

I've got a PHP array that outputs like this: Array ( [0] => Array ( [title] => Much title [end] => Such end [start] => Very start ) [1] => Array ( [title] ...

What is causing the TypeScript error in the MUI Autocomplete example?

I am attempting to implement a MUI Autocomplete component (v5.11) using the example shown in this link: import * as React from 'react'; import TextField from '@mui/material/TextField'; import Autocomplete from '@mui/material/Autoco ...

Exploring Angular JS: Understanding the Framework's Structure and FAQs

After diving into the world of AngularJS and familiarizing myself with its tutorial and documentation, I find myself in need of guidance on organizing the structure of my project. My goal is to create a single page app with different main sections such as ...

Leveraging the sibling combinator for altering the class of a sibling SVG element with the assistance of Material

I have created an SVG picture that I am trying to animate. Behind the elements I want to animate on mouse hover, I have added transparent rectangles. The hover effect works well on these elements as the cursor changes to pointer. However, when I attempt t ...

How to Serialize a Dictionary in C# Without Using the "key" and "value" Keywords

I am having difficulty serializing the data structure shown below into JSON: public class TestClass { public TestClass() { Translations = new List<Dictionary<string, Dictionary<string, string>>>(); } [JsonProp ...

perform action following a $router.go in Vue

Looking for guidance on how to properly execute a function after navigating back using this.$router.go(-1). I attempted using nextTick, but it doesn't seem to be the right approach. Any suggestions? ...

What are the ways to utilize the insertedCount function in MongoDB?

Whenever I navigate to the route "/new-article", an article gets stored in the database successfully, however, the server does not respond back to the client. Upon investigating, I found that the issue lies with the constant 'ris' missing the &ap ...

Navigating through JSON Serialization in Django and Unpacking JSON Data in Jquery

So here's the code snippet that I'm currently working with: def success_comment_post(request): if "c" in request.GET: c_id = request.GET["c"] comment = Comment.objects.get(pk=c_id) model = serializers.serialize("json" ...

Having trouble installing gatsby-plugin-transition-link using npm

https://i.stack.imgur.com/DyZxQ.png I'm facing some issues while trying to install gatsby-plugin-transition-link using npm. No matter what solutions I've attempted, the errors persist. Can anyone provide insight into what might be causing this p ...

It's quite baffling: How come the arrangement of my objects becomes disorganized following an ajax request even though I haven't made any modifications?

I am experiencing an issue where the objects retrieved from two nested ajax calls to the server are not in ascending order despite being ordered correctly by the server. The first ajax call successfully returns XML data with objects sorted by date in ascen ...

How to assign attributes and their corresponding values to an object in Node.js

Having trouble updating the object retrieved from a MongoDB database in NodeJs with additional properties and values This project is built using NodeJs. There are several items stored in the cart table within the MongoDB database. The process involves fet ...

Loading texts with the same color code via ajax will reveal there are differences among them

I am currently designing a webshop with green as the primary color scheme. Everything is functioning perfectly, but I have noticed that the text within an ajax loaded div appears brighter than it should be. The text that loads traditionally is noticeably d ...

The filtering and sorting features of Ng-table do not seem to be working properly when dealing with grouped data

Currently, I am in the process of learning angular.js and have recently started using the ng-table directive. While I have successfully managed to group my data and display it using ng-table, I seem to be facing issues with sorting and filtering the data. ...

Bootstrap modal with sticky-top class displays abnormal margin and padding upon being shown

Whenever I launch a bootstrap modal, I notice unexpected side padding or margin appearing on certain HTML elements. For instance: Before displaying the modal: <div id="fixedMenu" class="d-none container-fluid menu sticky-top px-0" s ...