猿问

js数据结构转换

如何用ES5将形如以下的数据结构:

[{obj0:"2016-12-01",obj1:"交通事故",obj2:"218"},{obj0:"2016-12-01",obj1:"医疗事故",obj2:"1"},{obj0:"2016-12-02",obj1:"交通事故",obj2:"200"},{obj0:"2016-12-02",obj1:"医疗事故",obj2:"5"}]

转化成

[{'2016-12-01':['交通事故':'218','医疗事故':'1']},{'2016-12-02':['交通事故':'200','医疗事故':'5']}]

这样的结构呢?

繁花不似锦
浏览 600回答 1
1回答

摇曳的蔷薇

let data = [{obj0:"2016-12-01",obj1:"交通事故",obj2:"218"},{obj0:"2016-12-01",obj1:"医疗事故",obj2:"1"},{obj0:"2016-12-02",obj1:"交通事故",obj2:"200"},{obj0:"2016-12-02",obj1:"医疗事故",obj2:"5"}],    res = {};for (let item of data) {    let obj = res[item.obj0] || {};    obj[item.obj1] = item.obj2;    res[item.obj0] = obj;}console.log(JSON.stringify(res))// {"2016-12-01":{"交通事故":"218","医疗事故":"1"},"2016-12-02":{"交通事故":"200","医疗事故":"5"}}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答