2015-10-07 4 views
0

У меня возникли проблемы с подсчетом количества объектов в этом массиве в javascript. Ниже представлен массив объектов, которые я пытаюсь подсчитать с помощью моего кода.Цитирование по списку массивов для подсчета объектов

 <script> 

var arr = [ 
    {"gateways":["ccu1"],"manufacturer":["homematic"],"ir":["ir_no"],"ip":["ip_cam","ip_other"]}, 
    {"gateways":["v3"],"manufacturer":["homematic"],"ir":["ir_no"],"ip":["ip_cam"]}, 
    {"gateways":["v2","v3","v4","ccu2"],"manufacturer":["homematic","intertechno"],"ir":["ir_yes"],"ip":["ip_cam","ip_other"]}, 
    {"gateways":["v2","ccu1","ccu2"],"manufacturer":["homematic"],"ir":["ir_yes"],"ip":["ip_cam","ip_other"]}, 
    {"gateways":["gw_none"],"manufacturer":["homematic"],"ir":["ir_no"],"ip":["ip_cam"]}, 
    {"gateways":["v3","ccu2"],"manufacturer":["homematic","fs20","intertechno","elro","Eltako Enocean"],"ir":["ir_yes"],"ip":["ip_cam","ip_other"]}, 
    {"gateways":["v3","v4"],"manufacturer":["homematic"],"ir":["ir_no"],"ip":["ip_other"]}, 
    {"gateways":["v3","v4"],"manufacturer":["homematic"],"ir":["ir_no"],"ip":["ip_other"]}, 
    {"gateways":["v2"],"manufacturer":["intertechno"],"ir":["ir_yes"],"ip":["ip_other"]} 
]; 
var counter = []; 
for(var i=0; i<arr.length; i++) { 
    //console.log(arr[i]); 

    for(var index in arr[i]) { 
     console.log(index); 

     if(counter[index] === undefined) { 
      counter[index] = []; 
     } 

    } 
} 
console.log(counter); 
    </script> 

Я хочу, чтобы количество объектов вдавливалось в пустой счетчик массива при консолидации журнала «счетчик», например.

шлюзы
CCU2 42 v4 70 v2 95 v3 91 v4plus 32 ccu1 16 gw_none 10

ф
ip_cam 4 ip_other 10 ip_none 4

ИК
ir_yes 13 ir_no 18

производитель
homematic 24 FS20 59 intertechno 38 ELRO 63 homeeasy 40 SOMFY 11

Я новичок в программировании и пытается мои руки на некоторых несколько упражнений, как этот, но я застрял. Я остался с кодами, чтобы поместить счетчик объектов в пустой массив. Я попытался, но не могу позволить этому работать. Я был бы признателен за любую помощь, и я надеюсь, что мое задание имеет смысл и понятно.

+1

Нет объектов 'arr.length' в массиве? –

+0

Начните с инициализации 'counter' как объекта, а не массива, т. Е.' Var counter = {}; '. Массивы используют числовые клавиши, в то время как вы хотите использовать строки в качестве ключей. http://jsfiddle.net/frsbawwz/ – pawel

ответ

0

Изменить это:

if(counter[index] === undefined) { 
     counter[index] = []; 
} 

Для этого:

if(counter[index] === undefined) { 
     counter[index] = []; 
} 
counter[index].push(arr[i][index]); 
0

Надежда этот код является полезным.

var arr = [ 
 
    {"gateways":["ccu1"],"manufacturer":["homematic"],"ir":["ir_no"],"ip":["ip_cam","ip_other"]}, 
 
    {"gateways":["v3"],"manufacturer":["homematic"],"ir":["ir_no"],"ip":["ip_cam"]}, 
 
    {"gateways":["v2","v3","v4","ccu2"],"manufacturer":["homematic","intertechno"],"ir":["ir_yes"],"ip":["ip_cam","ip_other"]}, 
 
    {"gateways":["v2","ccu1","ccu2"],"manufacturer":["homematic"],"ir":["ir_yes"],"ip":["ip_cam","ip_other"]}, 
 
    {"gateways":["gw_none"],"manufacturer":["homematic"],"ir":["ir_no"],"ip":["ip_cam"]}, 
 
    {"gateways":["v3","ccu2"],"manufacturer":["homematic","fs20","intertechno","elro","Eltako Enocean"],"ir":["ir_yes"],"ip":["ip_cam","ip_other"]}, 
 
    {"gateways":["v3","v4"],"manufacturer":["homematic"],"ir":["ir_no"],"ip":["ip_other"]}, 
 
    {"gateways":["v3","v4"],"manufacturer":["homematic"],"ir":["ir_no"],"ip":["ip_other"]}, 
 
    {"gateways":["v2"],"manufacturer":["intertechno"],"ir":["ir_yes"],"ip":["ip_other"]} 
 
]; 
 

 

 
var types = Object.keys(arr[0]); //Returns ["gateways","manufacturer","ir","ip"] 
 
var counter = {}; 
 
types.forEach(function(type){ 
 
    var values = [].concat.apply([], arr.map(function(d){ return d[type] })); // Find all values for each key like gateways 
 
    //Count occurrence of each value 
 
    var counts = {}; 
 
    for(var i = 0; i< values.length; i++) { 
 
    var num = values[i]; 
 
    counts[num] = counts[num] ? counts[num]+1 : 1; 
 
    } 
 
    counter[type] = counts; 
 
}); 
 

 
alert(JSON.stringify(counter));

Выход Получено:

{ 
    "gateways": { 
     "ccu1": 2, 
     "v3": 5, 
     "v2": 3, 
     "v4": 3, 
     "ccu2": 3, 
     "gw_none": 1 
    }, 
    "manufacturer": { 
     "homematic": 8, 
     "intertechno": 3, 
     "fs20": 1, 
     "elro": 1, 
     "Eltako Enocean": 1 
    }, 
    "ir": { 
     "ir_no": 5, 
     "ir_yes": 4 
    }, 
    "ip": { 
     "ip_cam": 6, 
     "ip_other": 7 
    } 
} 
0

Спасибо, ребята, но я сел и подумал, что я получил то, что я пропал без вести;

 //first we initialised counter 
    var counter = []; 

    //we then loop over the big array 
    for(var i=0; i<arr.length; i++) { 

     //we save then the single objects 
     var obj = arr[i]; 

     // We then evaluate Object -> looping and count on each entry 
     for(var key in obj) { 

     //check whether there is already an entry for the respective 
     //index (gateways, Manufacturer etc) 
      if(counter[key] === undefined) { 
       counter[key] = []; 
      } 


      //Save the individual array of Object entries 
      var arr2 = obj[key]; 

      //Looping and counting the array 
      for(var k=0; k<arr2.length; k++) {      
       var entry = arr2[k]; 

       //Check whether there is already a counter for that 
       //item 
       if(counter[key][entry] === undefined) { 
        counter[key][entry] = 1; 
       } else { 
        counter[key][entry]++; 
       } 
      } 
     } 
    } 
    console.log(counter); 
Смежные вопросы