This topic created in 4466 days ago, the information mentioned may be changed or developed.
是一个json处理的问题;
问题:
var obj1 = [
{
userid: 'james',
status: 'open',
open_count: 2
},
{
userid: 'james',
status: 'pending',
pending_count: 3
},
{
userid: 'livid',
status: 'open',
close_count: 5
},
...
]
处理 obj1 生成 obj2:
[
{
userid: 'james',
open_count: 2,
pending_count: 3
},
{
userid: 'livid',
open_count: 5,
pending_count: 2
},
...
]
感觉很简单,但是没成功,多谢;
14 replies • 1970-01-01 08:00:00 +08:00
 |
|
3
gaodong Mar 4, 2014
用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 Mar 4, 2014
JSON.stringify(obj1); JSON.parse(JSON.stringify(obj1)); 哪个是你想要的效果?
|
 |
|
5
shenqi Mar 4, 2014
抱歉我看错题了,之前去面试的时候就是考这题目,题目不错。
|
 |
|
6
shenqi Mar 4, 2014 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。
|
 |
|
7
lijinma Mar 4, 2014
@ shenqi 多谢兄弟!!!你的思路很好,按你的思路,已经解决!!!!!! 再次感谢;
|
 |
|
8
yyfearth Mar 5, 2014
基本上就是用一个 Object (相当于HashTable) 根据 userid 做 index 就可以解决吧
|
 |
|
12
rexren Mar 5, 2014
典型的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; }, {});
|