Using Javascript, dynamically add multiple values to a key within a loop

In my code, I am trying to create an object for the frontend using a loop.

Within the loop, variables are set for user, hours, and timestamp, which I want to use to dynamically build the new object.

This is what I have attempted so far, but it's not working as expected. Any assistance in resolving this issue would be greatly appreciated. Thank you!

var Things = { /* big dump of data */ };
var usersHours = {};

for (var i = Things.length - 1; i >= 0; i--) {

    var user = Things[i].user;
    var hours = Things[i].hours;
    var timeStamp = Things[i].timeStamp;

    var hoursAdd = {};

    hoursAdd[timeStamp] = hours;
    usersHours[user] = hoursAdd;

};


// This is the desired final output structure

var usersHours = {

    user1 : {
        1406178757855 : 10:00,
        1406178743473 : 04:00,
        1406178759600 : 04:44
    },
    user2 : {
        1406178475847 : 01:30,
        1406193847384 : 07:00,
        1406984783487 : 08:44
    },
    user3 : {
        1406173847787 : 01:40,
        1406139847873 : 07:14,
        1406183748374 : 08:34
    }
}

Answer №1

To determine if the user has existing data, check for it and create a new blank object to store additional data if necessary. In the example provided, data with the same timestamp for a user will replace any existing data.

Items = [{
    user: "personA",
    hours: "5",
    timestamp: "12312312322"
  }, {
    user: "personA",
    hours: "2",
    timestamp: "12322312322"
  }, {
    user: "personA",
    hours: "1",
    timestamp: "12312392322"
  }, {
    user: "personB",
    hours: "5",
    timestamp: "12312312322"
  }, {
    user: "personB",
    hours: "2",
    timestamp: "12322312322"
  }, {
    user: "personB",
    hours: "1",
    timestamp: "12312319322"
  }, {
    user: "personC",
    hours: "5",
    timestamp: "12312312322"
  }, {
    user: "personC",
    hours: "2",
    timestamp: "12322312522"
  }, {
    user: "personC",
    hours: "1",
    timestamp: "123123222322"
  },
]

var usersData = {};
for (var j = Items.length - 1; j >= 0; j--) {

  var usr = Items[j].user;
  var hrs = Items[j].hours;
  var timeStmp = Items[j].timestamp;

  // Check if user data exists
  if (!usersData[usr]) {
    usersData[usr] = {};
  }
  
  // Store or update the user's data with the corresponding timestamp and hours
  usersData[usr][timeStmp] = hrs;

};

console.log(usersData);

Answer №2

When dealing with multiple dynamic values, it is recommended to opt for using an array over a key. Arrays have the capability to store various data whereas keys are limited to just one pair.

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

What is the best way to change a string into an integer using ConvertTo-Json?

I am currently using PowerShell to transform a CSV file into JSON format. The issue I am facing is that the CSV file includes double quotes around all values, including integers. How can I convert these wrapped integers to actual integer values during the ...

What is the process for opening and populating dialogs from dynamically mapped cards?

I have a unique array of JSON data that is connected to Material-UI (MUI) cards. Each card features a button that triggers a dialog to open. When clicking the button on a card, I aim to pass the specific value of GroupName into the dialog. In my case, ther ...

`Is it possible to extract JSON information using jQuery?`

I am struggling with parsing the JSON data from hello.json and integrating it into my current HTML file. Can anyone guide me on how to extract the data of investors, events, and price from hello.json and store them in three separate arrays? Please provid ...

Having trouble resolving this technical problem in Express.js and JavaScript programming

try { console.log('11111') const { data: { tasks }, } = await axios.get('/api/v1/tasks') console.log('22222 ' + await axios.get('/api/v1/tasks') ) console.log('33333 ' + tasks) https://i.sstatic.net/mLLV ...

What is the best way to update the state of a different component?

Snippet: var React = require('react'); var RecipeBox = require('./RecipeBox.jsx'); var AddRecipe = React.createClass({ handleClick: function () { RecipeBox.setState({ adding: false }); }, rend ...

Deleting an object from an array based on its property in React: A step-by-step guide

Trying to create a todo list where clicking on a delete button within a grandchild element triggers an event in the parent component, aiming to delete the corresponding entry in the array. Parent Component (with array and delete function) const tasks = [ ...

Encountering unexpected props in Components upon clicking links within React-router

I am currently developing a User page that displays individual profiles for each user. The profile page is functioning properly upon initial loading. However, I am facing an issue where if I am viewing the profile of user1 and then navigate to the profile ...

Successfully Determining User Identity with Ajax Authentication

Currently, I am facing a security issue with my login page that uses an Ajax request for user authentication. The password entered by the user is sent as plain text in the form data of the Ajax request, making it vulnerable to interception by sniffing tool ...

In SQL, setting default values in a string is a common practice

//I am attempting to incorporate default variables into my SQL string to avoid syntax errors when loading my code. However, for some reason, adding the if statement is not producing any results. {`var serversLength = Request.Form("servers").count; v ...

The v-for directive on a reactive Vuejs array is failing to render its elements

After much searching, I have identified the error and provided a brief explanation in the following paragraph. The code below resolves the error by changing the approach of the code rather than fixing the error itself. By defining the indexes of the array ...

What is the process for importing a submodule in webpack?

I've set up a React component in an npm package called 'share-sheet'. This component is managed by webpack with the following configuration: webpack.config.js ... output: { path: path.join(__dirname, '/dist'), filename: & ...

What is the best way to send a selected value from a dropdown in a Jade template to a REST API in a Node.js application

I am working with a Jade template that includes two dropdown menus and a Load button. The goal is to send the selected values from these dropdowns to my Node API when the user clicks on the Load button. Here's the code I have been trying: extends lay ...

JS call for Bootstrap 5 collapse toggle not functioning as expected

I'm exploring the use of JavaScript to display or hide a collapsible element without toggling between the two states. In other words, I want to prevent the toggle functionality. According to the information provided in the documentation at https://ge ...

PHP: Extracting the selected value from a dropdown menu and incorporating it into an HTML link

Initially, I created a dropdown list Yet, there is uncertainty surrounding how to incorporate the selected choice (variable) into the input of the HTML <p style="text-align:center"> COVID-19 Checker</p> <br> <label for ...

Retrieving Data from JSON Object in Objective C

Currently working with objective c and facing an issue.. ( { error = 0; newsletter = ( { date = "2015-11-23"; description = "Lorem Ipsum is simply dummy text of the p ...

AngularJS redirection not fully functional

Having trouble with redirect in angularJS? For instance, everything works smoothly when a user logs in. If the user is logged in (information stored in local storage), they are automatically redirected to '/dashboard'. However, when the user lo ...

MongoDB update operation is incomplete

My model includes fields such as "id," "liked," "likedBy," and "matched." I am updating my database to add an id based on hypothetical likes; it stores the target's id in the current user's liked field and the current user's id in the target ...

What is the best way to fix character encoding issues with native JSON in Internet Explorer 8

When working with JSON containing Unicode text, I encountered an issue with the IE8 native json implementation. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script> var stringified = JSON.stringify("สวัส ...

What causes Node's crypto module to generate varying outputs for identical strings?

I'm currently attempting to execute the following program: var crypto = require('crypto'); var a = crypto.createHash('md5').update('89Zr-J591').digest('hex'); var name = '89Zr−J591'; var b = crypto. ...

Filtering Results using Jquery in a List

I found and customized a code snippet online to create a list of strings pulled from a database using JSON. The list is working perfectly, but now I want to add a feature that allows users to filter the results by typing in a text box using jQuery. What wo ...