简体   繁体   中英

Javascript - Add multiple dynamic values to dynamic key in for loop

I have a loop which I want to compile an object for the frontend.

The loop sets a user, hours and timestamp variable from which I want to dynamically create the new object.

This is what I have so far which does not work as it obviously just replaces the user. Any help would be great as the best way to go about this, thanks.

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;

};


// example of wanted final output

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
    }
}

So you can test if the user already has data and if they don't create an blank object ready to except the new data being added. With the example below if any timestamps are the same for the same user then the data will be overridden.

 Things = [{ user: "user1", hours: "5", timestamp: "12312312322" }, { user: "user1", hours: "2", timestamp: "12322312322" }, { user: "user1", hours: "1", timestamp: "12312392322" }, { user: "user2", hours: "5", timestamp: "12312312322" }, { user: "user2", hours: "2", timestamp: "12322312322" }, { user: "user2", hours: "1", timestamp: "12312319322" }, { user: "user3", hours: "5", timestamp: "12312312322" }, { user: "user3", hours: "2", timestamp: "12322312522" }, { user: "user3", hours: "1", timestamp: "123123222322" }, ] 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; //test if user has already got data if (!usersHours[user]) { usersHours[user] = {}; } //set/or possibly override a timestamp for the user with the hours usersHours[user][timeStamp] = hours; }; console.log(usersHours); 

If you want multiple dynamic values, you'll want to use an array instead of a key. Keys have one pair, arrays can hold the data you need it to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM