js将数组 每个对象里面键值名key 相同的 放到新的数组中 一维数组转为charts 图时
当后端返回的数据格式为
const datas = [ { fast: '0', publish: '2222' }, { fast: '2', publish: '1111' }, { fast: '23', publish: '113122111' }, { fast: '123', publish: '1135564511' } ];
想转换为
[ { name: 'fast', type: 'line', data: ['0', '2', '23', '234']//fast中的所有数据 },{ name: 'publish', type: 'line', data: ['2222', '1111', '113122111', '1135564511']//publish 中的所有数据 }, ]
方法为
getData(arr) { const resultList = []; arr.forEach(item => { Object.keys(item).forEach(key => { const mustIndex = resultList.findIndex(itema => itema.name === key); if (~mustIndex) { resultList[mustIndex].data.push(item[key]); return; } resultList.push({ name: key, type: 'line', data: [item[key]] }); }); }); return resultList; },
转变↓