0

I have a loop thats looping through some data and getting some fiel values from it.

    for (var i = 0; i < mainData[0].main.length; i++) {

      var obj = mainData[0].main[i];
      var cars = obj.cars;
      console.log(cars);   
}

This is returning

26
65
34
12

etc

What I need is to put this in a format so it looks like this:

[26, 65, 34, 12]

How can I do this?

5
  • initialize an array and push value in it Commented Jul 27, 2016 at 13:44
  • where do you get obj.sub.cars from? Commented Jul 27, 2016 at 13:44
  • share the remaining code Commented Jul 27, 2016 at 13:45
  • How is obj.sub.cars changing with each iteration? Commented Jul 27, 2016 at 13:45
  • does cars contains a single value or an array? Commented Jul 27, 2016 at 13:53

3 Answers 3

1

You could just map the result and get an array.

cars = mainData[0].main.map(a => a.cars);

ES5

cars = mainData[0].main.map(function (a) { return a.cars; });
Sign up to request clarification or add additional context in comments.

Comments

0

You can try this

var result=[];

for (var i = 0; i < mainData[0].main.length; i++) {
  var cars = obj.sub.cars;
  result.push(cars);          
}
console.log(result); 

Comments

0

Print the array directly

If you are trying to print just the array, you can use console.log(array)instead of looping over everything in the array.

for example, assume this is the array.

var primes = [2,3,5,7];
console.log(primes);

will output [2,3,5,7]

Comments

Your Answer

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