2016-11-10 16 views
1

関数の1回のパスでamountusersを計算できるかどうか、このjavascriptスニペットがありますか?この関数をより簡潔にすることができます

root.children.forEach(function(v) { 

    v.amount = v.children.reduce(function(a, b) { 
     console.log(a); 
     return { 
      amount: a.amount + b.amount 
     } 
    }, { 
     'amount': 0 
    }).amount 

    v.users = v.children.reduce(function(a, b) { 
     console.log(a); 
     return { 
      users: a.users + b.users 
     } 
    }, { 
     'users': 0 
    }).users 

}) 
+0

あなたはコードがないか、実現か説明できますか? 「子供たち」とは何ですか? – Li357

+0

各root.childrenにはもう一度子がありますか? vは子供オブジェクトを含んでいるので、あなたはv.childrenを書いています... – Gerfried

+0

@AndrewLiそれはcsv入力から階層的なjsonファイルを構築するより大きな関数の一部です – whytheq

答えて

1

あなたは可能性があり、単一のArray#forEachループ。

var root = { 
 
     children: [ 
 
      { children: [ 
 
       { amount: 2, users: 3 }, 
 
       { amount: 7, users: 5 } 
 
      ]} 
 
     ] 
 
    }; 
 

 
root.children.forEach(function(v) { 
 
    v.amount = 0; 
 
    v.users = 0; 
 

 
    v.children.forEach(function(a) { 
 
     v.amount += a.amount; 
 
     v.users += a.users; 
 
    }); 
 
}); 
 
console.log(root);
.as-console-wrapper { max-height: 100% !important; top: 0; }

+2

このコードは現在動作していません - 両親が0 – whytheq

+0

dvと表示されていますので、お気軽にコメントしてください。 –

+0

コードを少し修正しましたか?それは今私のために機能します - ありがとう。おそらく私のようなjsのnoobyのために私の頭を上げるためには簡単ですので、私はおそらくあなたのソリューションを使用します! – whytheq

6

はい、あなたは文字通り一つに二つの方法を組み合わせることができますように

root.children.forEach(function(v) { 
    var obj = v.children.reduce(function(a, b) { 
     a.amount += b.amount; 
     a.users += a.users; 
    }, {'amount': 0, 'users' : 0 }); 
    v.amount = obj.amount; 
    v.users = obj.users; 
}); 
6

、以下のように見えますことを行うことができます。

root.children.forEach(function(v) {   
    var result = v.children.reduce(
     function(a, b) { 
      return { 
       amount: a.amount + b.amount, 
       users: a.users + b.users 
      }; 
     }, 
     { amount: 0, users: 0 } 
    ); //^Note that I left out the quotes there. In this case, they're optional. 

    v.amount = result.amount; 
    v.users= result.users; 
}); 
+0

私は可能と思っていたものを組み合わせています - jsの基本は実装が難しいということを知っていませんでした! – whytheq

関連する問題