var rowData=[ {data:4,date:'06',code:'cr_3',name:'桥吊3'}, {data:1,date:'03',code:'cr_1',name:'桥吊1'}, {data:2,date:'01',code:'cr_2',name:'桥吊2'}, {data:1,date:'07',code:'cr_1',name:'桥吊1'}, {data:2,date:'02',code:'cr_2',name:'桥吊2'}, {data:1,date:'09',code:'cr_1',name:'桥吊1'}, {data:2,date:'03',code:'cr_2',name:'桥吊2'} ]; var arr=rowData.reduce(function(o,v,i){ if(o[v.code]){ o[v.code].push(v.data); }else{ o[v.code]=[v.data]; } return o; },{}) console.log(arr);
返回的结果
{
"cr_1":[1,1,1],
"cr_2":[2,2,2],
"cr_4":[4]
}
例子:得到字符串数据 “ str1/str2/str3”
需要获取用户选中数的id,拼接成字符串的格式传到后台,原始的做法是在后面加一个字符串,但是这样在最后的时候就需要剪切一次,现在换成在前面拼接“\”(不用转义有时候会报错)
var data=obj; var nodes=treeObj.getCheckedNodes(true);//获取ztree选中的树 data.groupTreeCode=nodes.reduce(function(o,v,i){ if(!!0){o+="\"} o+=v.original_id; return o; })
如下:只是获取选中的叶子节点的id
var data=obj; var nodes=treeObj.getCheckedNodes(true);//获取ztree选中的树 data.groupTreeCode=nodes.reduce(function(o,v,i){ if(!!o){o+="\"} o+=v.original_id; return o; })
简单替换for循环
var rowData=[{id:11,text:"千瓦时1"},{id:22,text:"千瓦时2"},{id:33,text:"千瓦时3"}] var obj=rowData.reduce(function(o,v,i){ debugger; o[v.id]=v.text; return o; },{}) console.log(obj);//{11,"千瓦时1",22,"千瓦时2",33,"千瓦时3"}