Javascript - 在for循环中为动态键添加多个动态值

时间:2014-11-10 04:04:53

标签: javascript arrays json javascript-objects

我有一个循环,我想为前端编译一个对象。

循环设置用户,小时和时间戳变量,我想从中动态创建新对象。

这是我到目前为止无法正常工作,因为它显然只是取代了用户。任何帮助都是最好的解决方法,谢谢。

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

2 个答案:

答案 0 :(得分:3)

因此,您可以测试用户是否已拥有数据,以及他们是否创建了一个空白对象,除了要添加的新数据之外。使用下面的示例,如果同一用户的任何时间戳相同,则数据将被覆盖。

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);

答案 1 :(得分:0)

如果您想要多个动态值,则需要使用数组而不是键。密钥有一对,数组可以保存您需要的数据。