简体   繁体   中英

Javascript change format from looping into array format

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?

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

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM