1

I have the below list of array:

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

How do I convert the above into an object array like below:

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

So far, I've tried to use below coding to convert but failed:

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

Do you guys know how?

3
  • Why don't you create the desired structure in the first place? Initialize objects and push them into an array. Commented Jun 25, 2016 at 7:04
  • How do we initialize? Commented Jun 25, 2016 at 7:08
  • This article covers it: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jun 25, 2016 at 7:09

3 Answers 3

1

Initialize abc[0] as an object then updates it's property.

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

console.log(abc);

or initialize it with all object property.

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

console.log(abc);

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

Basically your number,counter, time array is like this.

You can use forEach array method to loop through each of the object and fill the abc array, item & index are parameters which are accepted by forEach function

    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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.