2017-05-08 3 views
-1

オブジェクトを読み、名前でグループ化し、それぞれの発生をカウントするのに助けが必要です。JavaScriptオブジェクトプロパティ別にグルーピングして新しいオブジェクトにプッシュ

次に、ハンドルバーを使用して反復できる別のオブジェクトに結果をプッシュする必要があります。私は名前をそれをループますいくつかのコードを発見し、アップ集計している

var names = [ 
{ "name": "Person A" }, 
{ "name": "Person B" }, 
{ "name": "Person C" }, 
{ "name": "Person D" }, 
{ "name": "Person B" }, 
{ "name": "Person C" }, 
{ "name": "Person B" } 
]; 

 for(var i = 0; i < names.length; i++) { 

      if(!count[names[i].name]){ 
       count[names[i].name] = 0;      
      } 
      count[names[i].name]++; 
     }  

次私に与える:

enter image description here

は、ここに私のサンプル・オブジェクトの

これらの結果を新しいオブジェクトfにプッシュする必要がありますまたはハンドルバーを読む。だから私は、この形式であるデータを必要とする:

enter image description here

これは私がこれまで管理してきたものですが、私は新しいアイテムとしての私の応答オブジェクトにデータをプッシュするために苦労しています。カウントオブジェクトから名前と合計を取得する方法がわかりません。

// Set up the data to be returned 
var names = [ 
{ "name": "Person A" }, 
{ "name": "Person B" }, 
{ "name": "Person C" }, 
{ "name": "Person D" }, 
{ "name": "Person B" }, 
{ "name": "Person C" }, 
{ "name": "Person B" } 
]; 
var count = {}; 
var response = { items:[] }; 



     for(var i = 0; i < names.length; i++) { 

      if(!count[names[i].name]){ 
       count[names[i].name] = 0;      
      } 
      count[names[i].name]++; 
     }    


// Loop through the count object and populate response items 
for(var key in count) { 

    response.items.push({ 
      // How do i put the name and total here? 
      "name": "Person A", 
      "total": 12345 
    }); 
} 


console.log(count); 
console.log(response); 

答えて

3

これはあなたの期待ですか?以下のような 使用forinループ:

for (var key in count) { 
    response.items.push({ 
     "name": key, 
     "total": count[key] 
    }); 
} 
+0

はい、これは完璧です、ありがとうございました – Scott

0

あなたはこれを行うことができます。

var names = [{ 
 
    "name": "Person A" 
 
    }, 
 
    { 
 
    "name": "Person B" 
 
    }, 
 
    { 
 
    "name": "Person C" 
 
    }, 
 
    { 
 
    "name": "Person D" 
 
    }, 
 
    { 
 
    "name": "Person B" 
 
    }, 
 
    { 
 
    "name": "Person C" 
 
    }, 
 
    { 
 
    "name": "Person B" 
 
    } 
 
]; 
 

 
var count = {}; 
 
for (var i = 0; i < names.length; i++) { 
 

 
    if (!count[names[i].name]) { 
 
    count[names[i].name] = 0; 
 
    } 
 
    count[names[i].name]++; 
 
} 
 

 
var res = []; 
 
for(var i in count) { 
 
    if(count.hasOwnProperty(i)) { 
 
    res.push({name:i, total:count[i]}); 
 
    } 
 
} 
 
console.log(res);

0

const names = [ 
 
{ "name": "Person A" }, 
 
{ "name": "Person B" }, 
 
{ "name": "Person C" }, 
 
{ "name": "Person D" }, 
 
{ "name": "Person B" }, 
 
{ "name": "Person C" }, 
 
{ "name": "Person B" } 
 
] 
 

 
const count = names.reduce((count, item) => (
 
    count[item.name] 
 
    ? count[item.name]++ 
 
    : count[item.name] = 1 
 
    , count) 
 
, {}) 
 

 
const result = Array.from(Object.keys(count), (key) => ({ name: key, total: count[key] })) 
 

 
console.log(result)

関連する問題