js,遍历json数组 求和 跪求大神帮忙解决
你好,刚刚问的问题都不用看了帮忙看下这个?vara=[{"id":"0000","name":"ROOT","age":1,"pjz":2,"children":[{"i...
你好,刚刚问的问题 都不用看了 帮忙看下这个?
var a = [ {
"id" : "0000",
"name" : "ROOT",
"age" : 1,
"pjz" : 2,
"children" : [ {
"id" : "1000",
"name" : "1年",
"age" : 2,
"pjz" : 3,
"children" : [ {
"id" : "1001",
"name" : "1年1",
"age" : 3,
"pjz" : 5
} ]
}, {
"id" : "2000",
"name" : "2年",
"age" : 4,
"pjz" : 8
} ]
} ];
var b = [ {"field" : "age","type" : "sum"},{"field" : "pjz","type" : "default"},{"field" : "id","type" : "default"}];
由a,b得到c,若a中节点的值在b中类型为sum的进行求和
var c = [ {
"id" : "0000",
"name" : "ROOT",
"age" : 6,为1+2+3(本身的值加上子节点age的值)
"pjz" : 2,
"children" : [ {
"id" : "1000",
"name" : "1年",
"age" : 5,为2+3(本身的值加上子节点age的值)
"pjz" : 3,
"children" : [ {
"id" : "1001",
"name" : "1年1",
"age" : 3,为3(本身的值加上子节点age的值)
"pjz" : 5
} ]
}, {
"id" : "2000",
"name" : "2年",
"age" : 4,为4(本身的值加上子节点age的值)
"pjz" : 8
} ]
} ]; 展开
var a = [ {
"id" : "0000",
"name" : "ROOT",
"age" : 1,
"pjz" : 2,
"children" : [ {
"id" : "1000",
"name" : "1年",
"age" : 2,
"pjz" : 3,
"children" : [ {
"id" : "1001",
"name" : "1年1",
"age" : 3,
"pjz" : 5
} ]
}, {
"id" : "2000",
"name" : "2年",
"age" : 4,
"pjz" : 8
} ]
} ];
var b = [ {"field" : "age","type" : "sum"},{"field" : "pjz","type" : "default"},{"field" : "id","type" : "default"}];
由a,b得到c,若a中节点的值在b中类型为sum的进行求和
var c = [ {
"id" : "0000",
"name" : "ROOT",
"age" : 6,为1+2+3(本身的值加上子节点age的值)
"pjz" : 2,
"children" : [ {
"id" : "1000",
"name" : "1年",
"age" : 5,为2+3(本身的值加上子节点age的值)
"pjz" : 3,
"children" : [ {
"id" : "1001",
"name" : "1年1",
"age" : 3,为3(本身的值加上子节点age的值)
"pjz" : 5
} ]
}, {
"id" : "2000",
"name" : "2年",
"age" : 4,为4(本身的值加上子节点age的值)
"pjz" : 8
} ]
} ]; 展开
1个回答
展开全部
var Sum = function(List,Field)
{
var S = 0,T,F;
for (F = 0;F < List.length;++F)
{
T = List[F]
T.children && (T[Field] += Sum(T.children,Field))
S += T[Field]
}
return S
},F;
for (F = b.length;F--;)
{
switch (b[F].type)
{
case 'sum' : Sum(a,b[F].field)
}
}
追问
不好意思 请问如果"age"的值为字符串 在代码哪边转换成数字类型 帮忙看下哈 没找到
追答
如果你的age是字符串类型
那麽
var Sum = function(List,Field)
{
var S = 0,T,F;
for (F = 0;F < List.length;++F)
{
T = List[F]
T[Field] = parseFloat(T[Field])
T.children && (T[Field] += Sum(T.children,Field))
S += T[Field]
}
return S
},F;
for (F = b.length;F--;)
{
switch (b[F].type)
{
case 'sum' : Sum(a,b[F].field)
}
}
来自:求助得到的回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询