How can I convert an Array into a Dictionary using JavaScript?

Is there a clever method (perhaps using a map function) to restructure my data object from this:

[
  {id: 1, from: "1/1/2021", to: "1/2/2022"},
  {id: 2, from: "1/3/2021", to: "1/4/2022"},
  {id: 1, from: "1/5/2021", to: "1/6/2022"},
  {id: 2, from: "1/6/2021", to: "1/7/2022"}
]

to the following format:

{
  1: [{from: "1/1/2021", to: "1/2/2022"}, {from: "1/5/2021", to: "1/6/2022"}],
  2: [{from: "1/3/2021", to: "1/4/2022"}, {from: "1/6/2021", to: "1/7/2022"}]
}

Check out the code snippet below for reference:

const res = [
  {id: 1, from: "1/1/2021", to: "1/2/2022"},
  {id: 2, from: "1/3/2021", to: "1/4/2022"},
  {id: 1, from: "1/5/2021", to: "1/6/2022"},
  {id: 2, from: "1/6/2021", to: "1/7/2022"}
]

let dict = {};
for(var i=0; i < res.length; i++) {
   dict[res[i].id] = dict[res[i].id] || [];
   dict[res[i].id].push({from:res[i].from, to:res[i].to});
}
console.log(dict);

Answer №1

To group by any property, such as id, you can implement a custom groupBy() function using Array.reduce() to transform the data into the desired object structure.

Note: In this updated version, we have excluded the specified property, in this case id, from the resulting grouped arrays.

let input = [ {id: 1, from: "1/1/2021", to: "1/2/2022"}, {id: 2, from: "1/3/2021", to: "1/4/2022"}, {id: 1, from: "1/5/2021", to: "1/6/2022"}, {id: 2, from: "1/6/2021", to: "1/7/2022"} ];

function groupBy(arr, property) {
    return arr.reduce((acc, cur) => {
        const { [property]: _, ...obj} = cur;
        acc[cur[property]] = [...(acc[cur[property]] || []), obj];
        return acc;
    }, {})
}

console.log(groupBy(input, 'id'))
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

You also have the option to utilize lodash groupBy for this purpose, requiring minimal code:

let input = [ {id: 1, from: "1/1/2021", to: "1/2/2022"}, {id: 2, from: "1/3/2021", to: "1/4/2022"}, {id: 1, from: "1/5/2021", to: "1/6/2022"}, {id: 2, from: "1/6/2021", to: "1/7/2022"} ];

console.log('groupBy (lodash):', _.groupBy(input, 'id'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>

Additionally, you can leverage reduce with a Map object for grouping purposes:

let input = [ {id: 1, from: "1/1/2021", to: "1/2/2022"}, {id: 2, from: "1/3/2021", to: "1/4/2022"}, {id: 1, from: "1/5/2021", to: "1/6/2022"}, {id: 2, from: "1/6/2021", to: "1/7/2022"} ];

function groupBy(arr, property) {
    return Object.fromEntries(arr.reduce((acc, cur) => { 
        return acc.set(cur[property], [...(acc.get(cur[property]) || []), cur]);
    }, new Map()))
}

console.log(groupBy(input, 'id'))
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

Answer №2

Using Array.reduce() method can provide a solution to your issue.

const data = [
  {id: 1, from: "1/1/2021", to: "1/2/2022"},
  {id: 2, from: "1/3/2021", to: "1/4/2022"},
  {id: 1, from: "1/5/2021", to: "1/6/2022"},
  {id: 2, from: "1/6/2021", to: "1/7/2022"}
];

var result = data.reduce(function(accumulator, {id, from, to}) {
  (accumulator[id] = accumulator[id] || []).push({from, to});
  return accumulator;
}, {});

console.log(result);

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

Convert a list into a hierarchical structure of nested objects

Working with angular, I aim to display a nested tree structure of folders in an HTML format like below: <div id="tree"> <ul> <li ng-repeat='folder in folderList' ng-include="'/templates/tree-renderer.html'" ...

Exploring the versatility of Grails 3 profiles through JSON rendering and implementing a One to Many relationship with

I am currently utilizing gson and web profile in my project. The domain I am working with is: package json import grails.rest.* @Resource(readOnly = false, formats = ['json', 'xml']) class Hero { String name String data S ...

The sequence of CSS and deferred JavaScript execution in web development

Consider this scenario: you have a webpage with a common structure in the <head>: <link rel="stylesheet" href="styles.css"> // large CSS bundle <script defer src="main.js"></script> // small JS bundle with defer attribute There is ...

Having trouble sending an array's JSON data to a web service using Angular

I am working with a table where each cell in the rows contains form fields. The table also has two buttons: one button adds a new row to the table, and the other sends all the rows. Below is the code snippet for adding new blank rows: $scope.attributes = ...

Updating a div using PHP elements

Currently, I'm using a webcam to capture images for a project related to learning. My goal is to showcase the recently taken photos. After taking a photo, it gets stored in a folder. To display all the collected photos within a <div>, I need to ...

NodeJS - The server returns a 404 error before ultimately displaying the requested page

I'm having trouble with my nodeJS application. When I make an asynchronous call using ajax, the server first responds with a 404 error before loading the page. The application functions properly, but I keep receiving repetitive logs stating "Can' ...

Using the React key attribute for components without distinct identifiers

When dealing with a situation where users need to provide a list of timeframes, it can be tricky to generate a unique key for each component in React. Simply using the index of the array is not sufficient, as items can be removed from the middle of the lis ...

Is it possible to modify the CSS of a single class when hovering over a child class of a different and unrelated class?

I am struggling with CSS combinators, especially when dealing with nested div, ul, and li elements. My issue involves changing the CSS of a div with the class "H" when hovering over li elements with the class "G". Since all of this is contained within a s ...

Tips for managing large amounts of data retrieval from an API

As a beginner, I am attempting to retrieve data from an API and display it using the v-for directive. However, this process is causing my app to lag. It freezes when new data is fetched or when I search within the list. The following code snippet shows whe ...

Troubleshooting the issue of missing object in Django template

I keep encountering the issue that json is not serializable. views.py def get_post(request): if request.is_ajax(): if request.method=="GET": craves = CraveData.objects.filter(person=request.user) print craves ...

Creating a RESTful API

To begin with, I am a newcomer to web frameworks and we are currently using Meteor. In our database, we have a collection of Students: Students = new Mongo.Collection('students'); At the moment, we have defined a Rest API as follows: // Maps t ...

Scrolling through a lengthy table without affecting the overall window scroll

I currently have a situation where I have a table positioned below several div elements: <div></div>...<div></div> <div id="tablecontent"> <table>...</table> </div> My goal is to make the table scrollable ...

Validate the date selected in a dropdown menu using JavaScript

I'm still relatively new to Javascript, just working my way through some tutorials. I have three select boxes in my HTML form as shown below. HTML Form: <table> <form id="enrolment" name="enrolment" onsubmit="return datevalidate();" action ...

"Enhance Your Website with Drag-and-Drop Cart Functionality using HTML

Seeking assistance from anyone who has the knowledge. I've searched through similar questions on this platform but haven't been able to resolve my issue. Currently, I'm working on developing a basic shopping cart using HTML5 (Drag and Drop ...

What is the best way to transfer my json file to the server?

How do I send a json file to the server using Flutter? { "likes":{ "job_name":"teh", "job_address":"teh" } , "equals":null } Upon trying to implement this, I enco ...

ajax receives an empty responseText after sending intermediate data to Python on the backend

Initially, the frontend passed an identification to the backend. The backend utilized this identification to retrieve data from the database. The extracted data then underwent additional processing on the backend before being sent back to the frontend. Be ...

Applying the Directive/Isolated Scope as Embedded HTML within an Angular-Bootstrap Popover

If you're using the angular-ui popover, you have the ability to include HTML content within it. However, I encountered some difficulties in placing a directive called sampleDirective inside the popover. Despite my attempts with the $sce.trustAsHtml an ...

Tips on restricting dates to be equal to or earlier:

I have written a code to determine if two given dates are equal or not. The code should allow for the current date to be smaller than or equal to the provided date, but it should not allow for it to be greater. var date = '10-11-2015'; var toda ...

When deserializing with Newtonsoft, the same date can sometimes produce varying outputs

Struggling with deserializing DateTime in JSON for my Xamarin app using Newtonsoft. It works fine in C# for asp.net, but not in Xamarin. In C#, the output is correct as expected: 2/4/2019 12:00:00 AM. However, in Xamarin, it shows a wrong date 4/1/2019 4: ...

Tips for having Ajax.Net PageMethod return JSON data

Using AJAX.Net, I am calling an ASP.Net PageMethod that returns JSON serialized data {"d":"[{\"Fromaddress\":\"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e09485939486928f8dd1a094859394ce838f8d">[email ...