Rumah > Soal Jawab > teks badan
var data1 = { "TemplateName": "数据规范", "SummaryFields": [ { "FieldName": "用户姓名", "FieldCode": "UDF_F_935", "Visable": true }, { "FieldName": "当前日期", "FieldCode": "UDF_F_936", "Visable": true }, { "FieldName": "ReportID", "FieldCode": "ReportID", "Visable": false } ], "Code": 0, "Message": null }; var data2 = { "TotalCount": 2, "ReturnData": [ { "UDF_F_935": "超级管理员", "UDF_F_936": "2009-05-01", "UDF_F_938": "admin", "UDF_F_942": "女", "UDF_F_943": "丙", "ReportID": "221" }, { "UDF_F_935": "超级管理员", "UDF_F_936": "2009-05-01", "UDF_F_938": "admin", "UDF_F_942": "男", "UDF_F_943": "乙", "ReportID": "220" } ], "Code": 0, "Message": null };
列表显示效果如下: 用户姓名:超级管理员, 当前日期:2009-05-01, ReportID:221 用户姓名:超级管理员, 当前日期:2009-05-01, ReportID:220
如何使用 javascript 构造列表相应的json数据?尽量提高性能
三叔2016-11-15 16:16:42
写着写着,发现一个抖机灵的方法- -,不过不咋严格
//主要做的是键值替换 function generate(title, data){ var keys = {}; //先把键值对取出来 title.SummaryFields.forEach(function(e){ keys[e.FieldCode] = { name:e.FieldName, Visable:e.Visable }; }); //console.log(keys); //把目标数组序列化 var res = JSON.stringify(data.ReturnData); for(var key in keys){ //正则替换掉那些键值,没有的属性我无视了= = res = res.replace(new RegExp(key,'g'), keys[key].name); } //console.log(JSON.parse(res)); return JSON.parse(res); } console.log(generate(data1,data2));
欧阳克2016-11-15 16:16:22
// es6 const map = data1.SummaryFields.reduce((r, t) => { r[t.FieldCode] = t.FieldName; return r; }, {}); const result = data2.ReturnData.map(m => { return Object.keys(m).reduce((r, key) => { const name = map[key]; if (name) { r[name] = m[key]; } return r; }, {}); });