JavaScript数组对象

时间:2016-01-16 15:05:08

标签: javascript arrays typescript

我写了一段打字稿代码。

CreateArray():any []
 {
  console.log("start");
    var array = [];
    var nameObjects = ["dave", "mike", "dave1", "mike1"];
       for (var j = 0; j < nameObjects.length; j++) {
          for (var i = 1; i < 9; i++) {
                array.push({
                    "hour": i, 
                    nameObjects
                })
            }
        }
        console.log(array);
        return array;
}

输出将是这样的:

{
hour: 1,
nameObjects :{"dave", "mike", "dave1", "mike1"}
},

 {
 hour: 2,
 nameObjects :{"dave", "mike", "dave1", "mike1"} 
 }

.....

{hour: 9,
  nameObjects :{"dave", "mike", "dave1", "mike1"} }
 }

我希望输出如下:

 {
hour: 1,
 dave:0,
 mike:0, 
 dave1:0,
 mike1:0
},
{
hour: 2,
 dave:0,
 mike:0, 
 dave1:0,
 mike1:0
},

我试图解决它,但我无法解决。请帮助克服这个问题

1 个答案:

答案 0 :(得分:2)

你的意思是这样吗?

console.log("start");
var array = [];
var nameObjects = ["dave", "mike", "dave1", "mike1"];

for (var i = 1; i < 9; i++) {
    var item = {
        hour: i
    };

    for (var j = 0; j < nameObjects.length; j++) {
        item[nameObjects[j]] = 0;
    }       
    array.push(item);
}

console.log(array);

[Playground]