JavaScript: Implement a function that returns an object with key-value pairs instead of a

Once again, I'm looking at this particular answer.

var firstEvents = events.reduce(function(ar, e) {
  var id = e.getId();
  if (e.isRecurringEvent() && e.isAllDayEvent() && !ar.some(function(f) {return f.eventId == id})) {
    ar.push({eventTitle: e.getTitle(), eventId: id, startDate: e.getAllDayStartDate(), endDate: e.getAllDayEndDate()});
  }
  return ar;
}, []);

If I want to obtain an array with the event titles as keys (Strings) and the start dates as values (Date objects), so that I can access a specific start date through firstEvents['some event title'], what modifications do I need to make?

EDIT:

Current Output:

firstEvents = [{eventTitle=Event title 1, <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="244152414a506d40195c5d5e1564434b4b4348410a474b49">[email protected]</a>, startDate=Sun Mar 18 00:00:00 GMT+01:00 2018, endDate=Mon Mar 19 00:00:00 GMT+01:00 2018},
               {eventTitle=Event title 2, <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="791c0f1c170d301d440100034b391e16161e151c571a1614">[email protected]</a>, startDate=Tue Mar 19 00:00:00 GMT+01:00 2019, endDate=Wed Mar 20 00:00:00 GMT+01:00 2019},
               {eventTitle=Event title 3, <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f49182919a80bd90c98c8d8ec7b4939b9b939891da979b99">[email protected]</a>, startDate=Fri Mar 20 00:00:00 GMT+01:00 2020, endDate=Sat Mar 21 00:00:00 GMT+01:00 2020}]

Desired Output (Pseudo):

firstEvents = ['Event title 1' => Sun Mar 18 00:00:00 GMT+01:00 2018,
               'Event title 2' => Tue Mar 19 00:00:00 GMT+01:00 2019,
               'Event title 3' => Fri Mar 20 00:00:00 GMT+01:00 2020]

Answer №1

Avoid using push, instead assign values to an object using keys.

obj = {}; // Make sure to adjust the source parameter if necessary
// It's not possible to change the type of input Array [] to Object {} within the function
// You can retrieve an Array and return an Object, but the source variable won't be modified
ar[e.getTitle()] = e.getAllDayStartDate();

Alternatively, consider utilizing some example data:

var obj = [
{
    eventTitle: 'one',
    eventId: '#1',
    startDate: new Date(),
    endDate: new Date()
},
{
    eventTitle: 'two',
    eventId: 'secondId',
    startDate: new Date(),
    endDate: new Date()
}];
var result = {};
for (var item of obj) {
    result[item.eventId] = item;
}
console.log(JSON.stringify(result, null, 2));
console.log(result['#1']);
console.log(result.secondId);

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

Tips on deleting CSS comments from a CSS file

Currently, I am utilizing nextjs + reactjs. My objective is to eliminate all CSS comments from my existing css file. Despite using next-purgecss in order to get rid of unnecessary CSS code, the comments are still persisting. What could be the reason behind ...

Set iframe or form to be in a fixed position

Having issues with my site where an iframe is contained within a div. When only one character is entered in the telephone box, validation fails and red warning text is displayed. Furthermore, after clicking in the email box and pressing tab twice, the fo ...

Node.js and react-create-app are not compatible with each other

I am currently using node.js version 14.6.0 and node-v version 7.20.0 To replicate the issue, follow these steps: npx create-react-app my-app2 Once everything is installed, run npm i After completing the above steps, you may encounter the following warn ...

Using ReactJS to trigger a timer function on a button click

Kindly Note: This is a unique query and not related to ReactJS - Need to click twice to set State and run function. The suggested solution there does not resolve my issue. This represents my original state: constructor(props) { super(props) this. ...

Any ideas on how to resolve this ajaxToolkit issue?

Just for your reference, here's what I'm trying to achieve: https://i.stack.imgur.com/GYaNz.jpg Error 1: Unknown server tag 'ajaxToolkit:CalendarExtender'. <ajaxToolkit:CalendarExtender FirstDayOfWeek="Monday" PopupPosition="Botto ...

What is the best way to fill out a secondary drop

Is it possible to dynamically populate a secondary selection based on the User's choice in the first selection? For example, if the user selects "Silver," how can I automatically remove "Silver" from the second selection options? var b = { img: ...

fill collections within backbone

Looking to optimize populating a Backbone collection, I have come across the push method but it requires iterating over all items: define([ ... ], function($, _, Backbone, imagesCollection, imageTemplate, gridView) { var AppView = Backbone.View.ex ...

Using TypeScript with React: Initializing State in the Constructor

Within my TypeScript React App, I have a long form that needs to dynamically hide/show or enable/disable elements based on the value of the status. export interface IState { Status: string; DisableBasicForm: boolean; DisableFeedbackCtrl: boolean; ...

Tips for preventing repetition in an array containing a mix of case-sensitive and case-insensitive strings using Swift

I am working on a tableview that showcases a list of objects of type String using Core Data. Users can continuously add new objects to the table, but I want to prevent duplicates from being added. I have successfully avoided exact duplicates like "Bank" an ...

Navigating through JSON data that has been returned

When I use AJAX (jQuery) to query my database, the data I receive back is causing some difficulties. While searching for a solution, I came across similar issues posted by others who pointed out that the PHP code (specifically how data is stored in the arr ...

Playing Tic Tac Toe - How to prevent displaying results when an invalid move is made

I'm currently facing an issue with determining valid input for playing the game again. It seems to display the game results right after showing an invalid entry, prompting the user to enter "y" or "n" once more. I've attached a picture to illustr ...

Tips for implementing React Browser Router within Material UI Drawer

I'm currently exploring how to implement Browser Router in React to populate the content section of a Material UI Drawer. While my code successfully links menu options to components displayed within the drawer's content section, a problem arises ...

What is the best method to transform URI data encoded in base64 into a file on the server side?

Looking for a solution to save a URI-data string as a jpg on the server using only Javascript. The alternative of writing it to a canvas and reading the image from there is not ideal. Any ideas? ...

Exploring the concept of importing components from different pages in NextJS

I'm currently navigating the Next.JS framework and struggling to grasp the concept of importing data from a component page. Let's say I've created a page named example.js in my components folder, where I'm fetching data from an API to d ...

Is your Javascript navigation functioning properly on some submenus while encountering issues on others?

If you visit , you'll notice that it's a visually appealing site. The navigation submenus seem to be functioning properly, HOWEVER upon inspecting the element, you'll notice that under the PRICING tab, there are submenus that have the same c ...

What causes the menu icon to shift to the left upon clicking it?

I'm currently working on a website project that involves implementing a fixed navbar with jQuery sliding animation for the menu. However, I've encountered an issue where the "menu_icon" is getting pushed to the left every time the menu slides dow ...

Enable modification of form field once a personalized dynamic stamp has been applied

I currently have a functional custom dynamic stamp that includes multiple input fields prompting the user. My goal now is to integrate a form text field onto the stamp after it has been rendered. For example, if someone stamps everything except for the led ...

Manipulate documents in a Mongoose array by conditionally adding or removing elements

Upon receiving data from the front end, I am dealing with the following object: { name: "Test 1", sets: [1,2] } Mongo Schema: Sets name: { type: String }, tests : [{ type: Schema.Types.ObjectId, ref : 'Test' ...

assigning a numerical value to a variable

Is there a way to create a function for a text box that only allows users to input numbers? I want an alert message to pop up if someone enters anything other than a number. The alert should say "must add a number" or something similar. And the catch is, w ...

Check the Full Calendar to see if any events are scheduled for today

I have a group of users who need to save their availability. Currently, I am utilizing Full Calendar and looking for a way to prevent them from adding the same event multiple times on a single day. My tech stack includes VueJs and all events are stored in ...