Create a JSON array containing multiple objects and group their values by their respective names

Working on a JavaScript project where I need to group JSON object values dynamically based on a specific key word in the array.

Each object in the array contains time values.

The length of the array, called time_entries, can vary.

This array can have one or multiple objects in it.

The goal is to group the objects based on the time: Hours, minutes, seconds.

{
    "activities": [
        {
            "name": "player one",
            "time_entries": [
                {
                    "days": 0,
                    "end_time": "2019-09-30 15:19:43",
                    "hours": 01,
                    "minutes": 02,
                    "seconds": 11,
                    "start_time": "2019-09-30 14:17:58"
                },
                {
                    "days": 0,
                    "end_time": "2019-09-25 15:40:11",
                    "hours": 0,
                    "minutes": 20,
                    "seconds": 4,
                    "start_time": "2019-09-25 15:20:15"
                },
                {
                    "days": 0,
                    "end_time": "2019-09-25 16:10:15",
                    "hours": 0,
                    "minutes": 30,
                    "seconds": 4,
                    "start_time": "2019-09-25 15:40:11"
                },
               
#more objects can be added here

            ]
        },
        {
            "name": "player two",
            "time_entries": [
                {
                    "days": 0,
                    "end_time": "2019-09-30 19:18:51",
                    "hours": 0,
                    "minutes": 0,
                    "seconds": 52,
                    "start_time": "2019-09-30 19:17:58"
                },

#more objects can be added here

            ]
        },
        {
            "name": "player three",
            "time_entries": [
                {
                    "days": 0,
                    "end_time": "2019-09-30 19:19:09",
                    "hours": 0,
                    "minutes": 0,
                    "seconds": 58,
                    "start_time": "2019-09-30 19:18:51"
                },
                {
                    "days": 0,
                    "end_time": "2019-09-30 21:21:09",
                    "hours": 2,
                    "minutes": 1,
                    "seconds": 0,
                    "start_time": "2019-09-30 19:20:09"
                },

#more objects can be added here

            ]
        }
    ]
}

The desired output should look like this:

 [
        {
            "name": "player one",
            "time_entries": [
                {
                    "days": 0,
                    "end_time": "2019-09-25 16:10:15",
                    "hours": 01,
                    "minutes": 50,
                    "seconds": 19,
                    "start_time": "2019-09-30 14:17:58"
                }
            ]
        },
        {
            "name": "player two",
            "time_entries": [
                {
                    "days": 0,
                    "end_time": "2019-09-30 19:18:51",
                    "hours": 0,
                    "minutes": 0,
                    "seconds": 52,
                    "start_time": "2019-09-30 19:17:58"
                }
            ]
        },
        {
            "name": "player three",
            "time_entries": [
                {
                    "days": 0,
                    "end_time":"2019-09-30 21:21:09",
                    "hours": 2,
                    "minutes": 1,
                    "seconds": 58,
                    "start_time": "2019-09-30 19:18:51"
                }
            ]
        }
]

Answer №1

Here is a step-by-step guide on how to achieve this:

  • Begin by using the map() method to loop through the given activities and modify each activity's time_entries property accordingly.
  • The getTimeEntry() function accepts an array of time entries and calculates the earliest start time, latest end time, and total activity time in terms of days, hours, minutes, seconds.

let data = { "activities": [ { "name": "player one", "time_entries": [ { "days": 0, "end_time": "2019-09-30 15:19:43", "hours": 01, "minutes": 02, "seconds": 11, "start_time": "2019-09-30 14:17:58" }, { "days": 0, "end_time": "2019-09-25 15:40:11", "hours": 0, "minutes": 20, "seconds": 4, "start_time": "2019-09-25 15:20:15" }, { "days": 0, "end_time": "2019-09-25 16:10:15", "hours": 0, "minutes": 30, "seconds": 4, "start_time": "2019-09-25 15:40:11" } ] }, { "name": "player two", "time_entries": [ { "days": 0, "end_time": "2019-09-30 19:18:51", "hours": 0, "minutes": 0, "seconds": 52, "start_time": "2019-09-30 19:17:58" } ] }, { "name": "player three", "time_entries": [ { "days": 0, "end_time": "2019-09-30 19:19:09", "hours": 0, "minutes": 0, "seconds": 58, "start_time": "2019-09-30 19:18:51" }, { "days": 0, "end_time": "2019-09-30 21:21:09", "hours": 2, "minutes": 1, "seconds": 0, "start_time": "2019-09-30 19:20:09" } ] } ] };

let result = {};

result.activities = data.activities.map(item => {
  return {
    "name": item.name,
    "time_entries": [getTimeEntry(item.time_entries)]
  };
});

function getTimeEntry(timeEntries) {
  let earliestTime = timeEntries[0].start_time;
  let latestTime = timeEntries[0].end_time;

  // Find earliest start time and latest end time.
  timeEntries.forEach(entry => {
    if (new Date(entry.start_time) < new Date(earliestTime)) {
      earliestTime = entry.start_time;
    }

    if (new Date(entry.end_time) > new Date(latestTime)) {
      latestTime = entry.end_time;
    }
  });

  // Calculate total seconds.
  let seconds = timeEntries.reduce((totalSeconds, currentEntry) => {
    let seconds = 0;

    seconds += currentEntry.seconds;
    seconds += currentEntry.minutes * 60;
    seconds += currentEntry.hours * 60 * 60;
    seconds += currentEntry.days * 24 * 60 * 60;

    return totalSeconds + seconds;
  }, 0);

  // Convert total seconds to days, hours, minutes, and seconds.
  let days = Math.floor(seconds / (24 * 60 * 60));
  seconds = seconds % (24 * 60 * 60);
  let hours = Math.floor(seconds / (60 * 60));
  seconds = seconds % (60 * 60);
  let minutes = Math.floor(seconds / 60);
  seconds = seconds % 60;

  return {
    "start_time": earliestTime,
    "end_time": latestTime,
    "days": days,
    "hours": hours,
    "minutes": minutes,
    "seconds": seconds
  };
}

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

How can I pass a specific value, rather than the entire array, in a ReactJS dropdown menu?

I am facing a problem where the entire array is being passed as an argument when I call onchange after getting correct values in the dropdown. Instead of only receiving the selected value, e contains the whole array. Here is the code snippet that demonst ...

Data loss in the array

I have a task where I need to slice 3 elements from an array and store them in another array array = [1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1]; rows = 3; Here is the method I am using getVertWallStruct = (array, rows) => { let i = 1, ...

Having difficulty executing the command 'npm install -g expo-cli'

When attempting to execute npm install - g expo-cli on a Windows 10 machine, I am encountering issues. An error message keeps popping up and preventing me from proceeding. I'm in desperate need of assistance! npm WARN deprecated <a href="/cdn-cgi/ ...

Having issues with AngularJS ng-if when implemented within a Form

Is there a way to hide my form after it has been submitted using ng-if? I am facing an issue where clicking the 'See' button toggles the form on and off, but the same functionality does not work with the 'Add' button. Any insights on wh ...

Analyzing the original data form versus the modified data

I'm dealing with a form in React that utilizes react-hook-form and the useFieldArray method for adding dynamic steps. The challenge I'm facing is how to compare the original data passed to the form with the edited data, in order to make correspon ...

Extract the content of an element and incorporate it into a script (AddThis)

HTML: <div id="file-section"> <div class="middle"> <p class="description"> Lorem ipsum... </p> </div> </div> jQuery: var share_on_addthis = { description: $('#file-section ...

perform the directive function following the ng-cloak execution

I am having an issue with my content using the ng-cloak directive, as I would like to retrieve the height of an element using innerHeight() within a directive. However, when I use innerHeight(), the element is hidden by ng-cloak so the result is always 0. ...

Guide to delivering a PDF document from a controller

In my pursuit to send a PDF file from a Controller Endpoint using NestJs, I encountered an interesting issue. Without setting the Content-type header, the data returned by getDocumentFile function is successfully delivered to the user. However, when I do ...

Utilizing Odoo Point of Sale feature on product selection

Can someone help me identify the function that is triggered when a product is clicked on at the point of sale? I am looking to add some code that will automatically apply a discount when a product is added to an order. Appreciate any assistance! ...

Manipulating a specific element within an ng-repeat in AngularJS without affecting the others

I'm currently working on developing a basic single page application to monitor people's movements. While I've made good progress, I've encountered an issue with the click function in the child elements of each person div. When I try to ...

Mapping arguments as function values

Hello there, I have an array of objects that I am attempting to map through. const monthObject = { "March 2022": [ { "date": "2022-03-16", "amount": "-50", &q ...

How to properly format an HTML input box for numeric entry and ensure correct formatting of the minus sign

I need assistance with formatting an HTML text input box to only accept numeric values using JavaScript. Specifically, the input should allow digits, a minus sign, or a dot/comma (which will be converted to a dot). However, I want to prevent multiple conse ...

Make sure to include all enum type values within the function's body to ensure comprehensive coverage

I am defining an enumeration called ApiFunctions with values like "HIDE", "SET_READ_ONLY", and "DESCRIPTION". Also, I have a type ValueOfApiFunction that should include all values of ApiFunctions. Additionally, I have a logic that listens for messages on ...

Refreshing and enhancing Android contacts through the Expo project

For my current project, I am utilizing the Expo Contact module to automatically update contact information. Here is a part of my script that focuses on updating a selected phone number: const updateContact = async (callId, newCall) => { getSingleConta ...

Tips for running two elixir tasks consecutively?

Check out this piece of code: var gulp = require('gulp'), fs = require('fs'); gulp.task('taskOne', function() { return gulp.src('folder1/file1.js') .pipe(gulp.dest('folder2')); }); gulp.t ...

Is there a way for me to extract the true text content that is concealed within the page source code?

Is there a way to extract the hidden text "2015-10-31" from a webpage, even though it is not visible in the page source? I am able to scrape the right side of the HTML, but I need to access the value on the left side. I have tried using Selenium to automat ...

Creating a simulated callback function using Jest with a promise

I am currently testing a specific function within my component that is triggered only when the API request is successful. To provide some background, this function is called upon clicking a button: return onUpdate(params, setError, success, cancel); Once ...

Avoid refreshing AJAX on browser back navigation

Describing my current situation: I have a scenario with 2 pages: - On page 1, it sends a request using $.ajax to receive JSON data for display. Then there is a button that when clicked, takes me to page 2. - After clicking the button and transitionin ...

Webshot is unable to retain any images

I attempted to utilize the Node package Webshot. The function is being executed, "OK" is printed to the console, but no files are saved to the specified folder. What could I be overlooking? if (Meteor.isServer) { var webshot = Meteor.npmRequire(&apos ...

Ways to alter the div post user authentication

I'm in the process of developing a website with a single-page application setup. I'm utilizing Node.js for the backend and Angular for the frontend. The challenge I'm facing is displaying a specific div when a user is not logged in, and swit ...