Using a unique key to access a JSON object within a JavaScript club

I'm attempting to organize a cleaner JSON object by grouping multiple objects with the same IDs. Here's my approach: 1. Save the ID of the first object and compare it with subsequent IDs. 2. Loop through the array to identify matching IDs. If found, create a new array of names in a separate object, otherwise add to a new object with the stored names as a property. 3. Clear out the names field.

There were various conditions to consider, especially when dealing with the last element in the array. I'm seeking an efficient solution for this task. Due to its specific nature, I haven't found a similar issue on Stack Overflow.

The initial JSON Object looks like this:

[
{
    id: 1,
    name: 'John'
},
{
    id: 1,
    name: 'Jack'
},
{
    id: 2,
    name: 'Drake'
},
{
    id: 2,
    name: 'Joey'
},
{
    id: 3,
    name: 'Justin'
},
{
    id: 3,
    name: 'Rob'
}
]

I aim to group similar IDs together, resulting in a structure like this:

[{
    id: 1,
    names: [{
        name: 'John'
    },
    {
        name: 'Jack'
    }]
},
{
    id: 2,
    names: [{
        name: 'Drake'
    },
    {
        name: 'Joey'
    }]
},
{
    id: 3,
    names: [{
        name: 'Justin'
    },
    {
        name: 'Rob'
    }]
}]

Answer №1

To achieve this, you can utilize the Array#forEach method along with an object to store the hashes.

var data = [{ id: 1, name: 'John' }, { id: 1, name: 'Jack' }, { id: 2, name: 'Drake' }, { id: 2, name: 'Joey' }, { id: 3, name: 'Justin' }, { id: 3, name: 'Rob' }],
    grouped = [];

data.forEach(function (a) {
    if (!this[a.id]) {
        this[a.id] = { id: a.id, names: [] };
        grouped.push(this[a.id]);
    }
    this[a.id].names.push({ name: a.name });
}, Object.create(null));

console.log(grouped);

Answer №2

Learn how to use the Array#reduce method in JavaScript along with an index reference object.

var data = [{  id: 1,  name: 'John'}, {  id: 1,  name: 'Jack'}, {  id: 2,  name: 'Drake'}, {  id: 2,  name: 'Joey'}, {  id: 3,  name: 'Justin'}, {  id: 3,  name: 'Rob'}];

// object for index reference
var ind = {};

// iterate over array
var res = data.reduce(function(arr, obj) {
  // check if index is already defined
  if (ind.hasOwnProperty(obj.id)) {
    // if defined, push the name value
    arr[ind[obj.id]].names.push({name: obj.name});
  } else {
    // if not defined, push a new object in the preferred format
    arr.push({ id: obj.id, names: [{ name: obj.name }] });
    // define the index in reference object
    ind[obj.id] = arr.length - 1;
  }
  // return the updated array
  return arr;
  // set initial value as an empty array
}, []);

console.log(res);

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

Node.js application encountering crashes while attempting to download a sizable file

I'm currently working on a project that involves converting HTTP URLs to torrents. The program is designed for downloading smaller files, typically between 1-500Mb. However, I've encountered an issue where the application crashes or times out whe ...

Tips for customizing your MUI slider design

import * as React from "react"; import Box from "@mui/material/Box"; import Slider from "@mui/material/Slider"; function valuetext(value) { return `${value}°C`; } export default function RangeSlider() { const [value, se ...

JavaScript: Use onclick events to change the class of a div on multiple divs

I have a jQuery script that allows for toggling of the parent class when #icon is clicked. Additionally, when the body is clicked, it reverts back to the original class. Now, I'm looking to achieve the same behavior when clicking on #item5 or #item4 a ...

Having trouble getting the jQuery AJAX post syntax to work properly

I am trying to send a post json value to another page using AJAX. However, when I include the "json" parameter in my POST request, the JavaScript code stops working. If I remove the "json" parameter, it works fine. I am still learning jQuery so any help ...

Having trouble with Laravel 5.5 and ajax file uploads?

I am encountering an issue with Laravel 5.5 while trying to get an ajax file. I can successfully receive the file using $_FILES, but $request->file() is not working as expected. Here is the code in question. Below are the HTML & Ajax elements: <htm ...

Is there a way to execute a JavaScript function on a webpage using Selenium automation?

Here's an element on a website: <span class="log-out-ico" ng-click="logout()"> Instead of clicking it, I want to run the "logout()" script from selenium. Is that possible? If so, how can I do it? This is what I attempted: I ...

Are you struggling with perplexing TypeScript error messages caused by a hyphen in the package name?

After creating a JavaScript/TypeScript library, my goal is for it to function as: A global variable when called from either JavaScript or TypeScript Accessible via RequireJS when called from either JavaScript or TypeScript Complete unit test coverage Th ...

HTML tends to disregard the dimensions specified in the JavaScript file

I'm currently working on replicating an Etch-a-Sketch style drawing board where hovering over a single pixel with the mouse changes its color. However, I've hit a roadblock when it comes to drawing the board. The flexbox container doesn't se ...

The HTML element containing a React variable is failing to render ASCII characters

I am encountering an issue where a custom title, received and set in a JS variable, is displaying the ASCII code instead of the symbol. To illustrate, here is a basic example of the render function: render() { var title = "My Title&#8482;" retur ...

Having trouble with installing npm package from gitlab registry

I recently uploaded my npm package to the GitLab package registry. While the upload seemed successful, I am facing an issue trying to install the package in another project. When I run npm install, I encounter the following error: PS E:\faq\medu ...

Ordering tables in jQuery with both ascending and descending options

Trying to sort a table in ascending and descending order using jQuery? Here's the JavaScript code for it. However, encountering an error: Cannot read property 'localeCompare' of undefined If you can provide guidance on how to fix this so ...

Tips for establishing communication between a React Native webView and a React web application

I am currently working on establishing communication between a webView in react-native and a web-app created with React-360 (and React). I am utilizing the react-native-webview library and following a guide for creating this communication. You can find the ...

Django AJAX call for data retrieval

Can someone assist me, please? I'm trying to update content on a page without refreshing when a button is clicked. Currently, my approach involves using the jQuery cookie plugin to save the button's id into a cookie and then reading that value in ...

Display a dynamic table using a JSON array in a React application

Looking to render the following jsonArray on a React page: [{ "machine1": [{ "Image": "mysql:latest", "Names": "mysql", "Status": "Restarting (1) 18 s ...

Sharing JSON data across different domains to ASP.NET using jQuery

I have encountered a complex issue. Currently, I am involved in a project that requires generating receipt printouts when users check out on our website at a kiosk. Due to driver and formatting challenges, I am utilizing COM automation with Word for handl ...

Separate JSON data into separate columns

Extracting a value from a parameter looks like the following: { "Line1":"Nav Place Road", "Line2":"Nyork City", "Line3":"USA 34576" } The desired display format is as follows: ColumnName Value --------------------------- Line1 Nav Place Road Line ...

What are some methods to showcase JSON information using only JavaScript either from a local JSON file or a web server?

Hello, I am new to working with JSON and I am curious to know if it is possible to use only JavaScript (without any frameworks) to present all the data from a JSON file in a table format. Preferably, I would like to load the file locally, but if using a w ...

Encountering difficulty inserting ajax response into a specific div element

What could be the issue? I've included the getElementById and I am receiving a response, as confirmed by Firebug. The response is correct, but for some reason it's not populating my div area. <script> $(document).ready(function () { $( ...

Guide on extracting and displaying the JSON data associated with a specific ID from a JSON file in Python

There is a json file containing the following data: { "A": "ID", "B": "Priority", "C": "Match URL", "D": "Match Query", "E": "Redirect URL", ...

Error Encountered While Serializing Products in getServerSideProps in Next.js v14

I am using Next.js version 14.2.3 and I am currently trying to retrieve a list of products from Firestore by utilizing the getProducts function from @stripe/firestore-stripe-payments within getServerSideProps. However, I am facing a serialization error: ...