1
lijinma OP <script src="https://gist.github.com/lijinma/9347166.js"></script>
|
2
lijinma OP 求大神帮帮忙 -。-
|
3
gaodong 2014-03-04 23:04:53 +08:00
用coffee写了一个,不知道还有没有简便的方式:
temp = {} for entry in obj1 temp[entry.userid]?= userid:entry.userid open_count:0 pending_count:0 temp[entry.userid].open_count += Number entry.open_count || 0 temp[entry.userid].pending_count += Number entry.pending_count || 0 console.log temp array = (v for k, v of temp) console.log array array 应该就是你要的结果 |
4
shenqi 2014-03-04 23:13:55 +08:00
JSON.stringify(obj1);
JSON.parse(JSON.stringify(obj1)); 哪个是你想要的效果? |
5
shenqi 2014-03-04 23:18:30 +08:00
抱歉我看错题了,之前去面试的时候就是考这题目,题目不错。
|
6
shenqi 2014-03-04 23:34:31 +08:00 1
var obj1 = [{
userid: 'james', status: 'open', open_count: 2 }, { userid: 'james', status: 'pending', pending_count: 3 }, { userid: 'livid', status: 'open', close_count: 5 }] function objConut(obj) { var returnObj = [], tempObj = {}, i, j, l, objI; for( i = 0, l = obj.length; i < l; i++){ objI = obj[i]; tempObj[objI.userid] = tempObj[objI.userid] || {} tempObj[objI.userid].userid = objI.userid; tempObj[objI.userid][objI.status+"_count"] = objI[objI.status+"_count"] + ( tempObj[objI.userid][objI.status+"_count"] || 0 ); } for( j in tempObj ){ returnObj.push( tempObj[j] ) } return returnObj; } objConut(obj1); try it。 |
8
yyfearth 2014-03-05 03:04:35 +08:00
基本上就是用一个 Object (相当于HashTable) 根据 userid 做 index 就可以解决吧
|
10
alexrezit 2014-03-05 07:16:41 +08:00
status 有用?
|
12
rexren 2014-03-05 12:27:24 +08:00
典型的reduce操作。如果有underscore的话:
var _ = require('lodash'); _.reduce(obj, function (memo, element) { if (!memo[element.userid]) { memo[element.userid] = {} } memo[element.userid][element.status+'_count'] = element[element.status+'_count']; return memo; }, {}); |