js遍历json数组,求大神指导(2)

varjson1=[{"age":5,"num":2,"people":3,"class":9},{"age":1,"num":3,"people":2,"class":... var json1=[{"age":5,"num":2,"people":3,"class":9},{"age":1,"num":3,"people":2,"class":8},{"age":4,"num":6,"people":5,"class":3}];
var json2=[{"field":"age","typle":"sum","title":"ss"},{"field":"num","typle":"sum","title":"ss"},
{"field":"people","typle":"sum","title":"ss"},{"field":"class","typle":"nosum","title":"ss"}];
如上json1、json2两个数组,拿json1里age、num等属性去json2里遍历,
若json2里field的值和json1的属性相等并且其typle的值为num,就计算json1里该属性的和
最终再拼接成下面的样子
var json3=[{"name":"求和","age":10,"num":11,"people":10}];

注:json1里属性未知不光有age、num、people、class只是举个例子

//没人会? 求大神帮忙写下
json3也是一个json数组
展开
 我来答
让猫飞一会儿
推荐于2016-08-23 · TA获得超过1120个赞
知道小有建树答主
回答量:540
采纳率:80%
帮助的人:278万
展开全部
<script src="http://vod.xunlei.com/library/jquery-1.7.2.min.js"></script>
<script>
var json1=[{"age":5,"num":2,"people":3,"class":9},{"age":1,"num":3,"people":2,"class":8},{"age":4,"num":6,"people":5,"class":3}];
var json2=[{"field":"age","typle":"sum","title":"ss"},{"field":"num","typle":"sum","title":"ss"},{"field":"people","typle":"sum","title":"ss"},{"field":"class","typle":"nosum","title":"ss"}];
//如上json1、json2两个数组,拿json1里age、num等属性去json2里遍历,若json2里field的值和json1的属性相等并且其typle的值为num,就计算json1里该属性的和最终再拼接成下面的样子
//var json3=[{"name":"求和","age":10,"num":11,"people":10}];

function test(json1,json2){
var result=[],resultJson={"name":"求和"};
var getSum=function(field){
var sum=0;
for(var s in json1){
sum+=json1[s][field]||0;
}
return sum;
}
for(var p in json2){
if(json2[p]["typle"]=="sum"){
$.extend(resultJson,$.parseJSON('{\"'+ json2[p]["field"] + '\":' + getSum(json2[p]["field"]) + '}'));
}
}
result.push(resultJson);
return result;
}

json3=test(json1,json2);
//检查一下结果
temp=""
for (var t in json3[0]){
temp+=t + "=" + json3[0][t] +",";
}
alert(temp.slice(0,-1)); //显示:name=求和,age=10,num=11,people=10
</script>
追问
谢谢哈
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式