将普通数组转换为html中的对象数组

时间:2016-06-25 07:01:40

标签: javascript jquery html arrays

我有以下数组列表:

var number = [];
var counter = [];
var time = [];

number[0] = "1212";
counter[0] = "2";
time[0] = "12:30PM";

number[1] = "9367";
counter[1] = "4";
time[1] = "05:30PM";

number[2] = "4786";
counter[2] = "8";
time[2] = "09:30AM";

如何将上述内容转换为如下所示的对象数组:

var abc = [
{number: "1212", counter: "2", time: "12:30PM"},
{number: "9367", counter: "4", time: "05:30PM"},
{number: "4786", counter: "8", time: "09:30AM"}
];

到目前为止,我已尝试使用以下编码进行转换但失败了:

var abc=[];
abc[0].number = "1212";
abc[0].counter = "2";
abc[0].time = "12:30PM";
你知道怎么样?

3 个答案:

答案 0 :(得分:1)

abc[0]初始化为对象,然后更新它的属性。

var abc = [];
abc[0] = {};
abc[0].number = "1212";
abc[0].counter = "2";
abc[0].time = "12:30PM";

console.log(abc);

或用所有对象属性初始化它。

var abc = [];
abc[0] = {
  number: "1212",
  counter: "2",
  time: "12:30PM"
}

console.log(abc);

答案 1 :(得分:1)

number.map(function(num,index) {
return {
number: number[index],
counter: counter[index],
time: time[index]
}
})

答案 2 :(得分:0)

基本上,您的number,counter, time数组就是这样。

您可以使用forEach数组方法遍历每个对象并填充 abc 数组,item & index是forEach函数接受的参数

    var number = ["1212","9367","4786"];
    var counter = ["2","4","8"];
    var time = ["12:30PM","05:30PM","09:30AM"];

    var abc =[];

    number.forEach(function(item,index){
    abc.push({
      name:number[index],
      counter:counter[index],
      time:time[index]
    })
    })

console.log(abc)

JSFIDDLE