前端對於數據的處理通常會用到foreach、map、reduce、Object.values()、Object.keys()、Object.entries()等方法,下面逐次進行分析前端
foreach
forEach() 方法用於調用數組的每一個元素,並將元素傳遞給回調函數。foreach方法不會返回執行結果。正則表達式
注意: forEach() 對於空數組是不會執行回調函數的。foreach會改變原數組。json
語法: array.forEach(function(currentValue, index, arr), thisValue)
示例: let schedulesObj = {}; dateArr.forEach((key) => { if (!schedulesObj[key]) { schedulesObj[key] = []; } schedulesObj[key].push(item); });
map
map() 方法返回一個新數組,數組中的元素爲原始數組元素調用函數處理後的值。數組
map() 方法按照原始數組元素順序依次處理元素。數據結構
注意: map() 不會對空數組進行檢測。app
注意: map() 不會改變原始數組。函數
語法: array.map(function(currentValue,index,arr), thisValue)
示例: const initItems = initEvaluateItems.map(item => { const { score, id, itemName, levelDesc, maxLevel } = item; return { score, id, itemName, levelDesc, maxLevel }; });
reduce
reduce() 方法接收一個函數做爲累加器,數組中的每一個值(從左到右)開始縮減,最終計算爲一個值。工具
reduce() 能夠做爲一個高階函數,用於函數的 compose。ui
注意: reduce() 對於空數組是不會執行回調函數的。this
語法: array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
示例: let scheduleIdArray = Object.keys(curScheduleMonth).map(v => curScheduleMonth[v]).reduce((total, item) => { total = [...total, ...item]; return total; }, []);
Object.keys()
Object.keys() 方法會返回一個由一個給定對象的自身可枚舉屬性組成的數組,數組中屬性名的排列順序和使用 for...in 循環遍歷該對象時返回的順序一致 。
語法: Object.keys(obj)
示例: var anObj = { 100: 'a', 2: 'b', 7: 'c' }; console.log(Object.keys(anObj)); // console: ['2', '7', '100']
Object.values()
Object.values()方法返回一個給定對象自身的全部可枚舉屬性值的數組,值的順序與使用for...in循環的順序相同 ( 區別在於 for-in 循環枚舉原型鏈中的屬性 )。
語法: Object.values(obj)
示例: var an_obj = { 100: 'a', 2: 'b', 7: 'c' }; console.log(Object.values(an_obj)); // ['b', 'c', 'a']
Object.entries()
Object.entries()方法返回一個給定對象自身可枚舉屬性的鍵值對數組,其排列與使用 for...in 循環遍歷該對象時返回的順序一致(區別在於 for-in 循環也枚舉原型鏈中的屬性)。
語法: Object.entries(obj)
示例: const anObj = { 100: 'a', 2: 'b', 7: 'c' }; console.log(Object.entries(anObj)); // [ ['2', 'b'], ['7', 'c'], ['100', 'a'] ]
1.時間相關
{ "success":true, "code": "success", "message": "成功", "data": { "monthData":[ { "month":"2018-05", "displayDesc":"有服務", "showType":"1", "tips":"請您選擇" } ] "calendarData":[ { "date":["2018-06-02","2018-07-09"], "displayDesc":"有服務", "showType":"1", "tips":"請您評價" } ], "schedules":[ { "scheduleId":"1", "appCode":"106", "appName":"公共服務", "cityId":"321568", "categoryCode":"16", "scheduleType":"1", "userDesc":"社區醫療", "systemDesc":"", "remind":"1", "repeat":"1", "status":"2", "serviceUrl":"", "beginTime":"2018-04-25", "endTime":"2018-04-26", } ] } }
import moment from 'moment/moment'; /** * 經過beginTime和endTime,將列表值按照天的維度進行整理,產出的數據結構scheduleByDay * @param schedules */ export function genSchedulesObj(schedules = []) { let schedulesObj = {}; schedules.forEach((item) => { let { beginTime, endTime } = item; let _beginTime = new Date(beginTime).getTime(); let _endTime = new Date(endTime).getTime(); let dateArr = []; let dateReduce = ((_endTime - _beginTime) / (1000 * 24 * 60 * 60) + 1) || 1; dateReduce > 0 ? {} : (dateReduce = 0); for (let i = 0; i < dateReduce; i++) { dateArr.push(moment(_beginTime).format('YYYY-MM-DD')); _beginTime += (1000 * 24 * 3600); } dateArr.forEach((key) => { if (!schedulesObj[key]) { schedulesObj[key] = []; } schedulesObj[key].push(item); }); }); // let flag = true; // for (let key in schedulesObj) { // for (let i = 0, len = schedulesObj[key].length; i < len; i++) { // if (schedulesObj[key][i].status < 3) { // flag = false; // break; // } // } // } return { schedulesObj }; } /** * calendarData 日期上顯示代辦內容,根據這個數據建立tagData是一個一維數組,產出的數據結構tagDataByMonth * @param calendarData */ export function genCalendarDataObj(calendarData = []) { let calendarDataObj = {}; calendarData.forEach((item) => { item.date.forEach((key) => { if (!calendarDataObj[key]) { calendarDataObj[key] = []; } calendarDataObj[key].push({ displayDesc: item.displayDesc, showType: item.showType }); }); }); return calendarDataObj; } /** * 獲取當前月、上一個月、下一月及當前月的開始、結束日期 */ export function getFormatMonth(currentDate) { const beginDate = moment(currentDate).startOf('month').add(-1, 'M').format('YYYY-MM-DD'); const endDate = moment(currentDate).endOf('month').add(1, 'M').format('YYYY-MM-DD'); const preMont = moment(currentDate).subtract(1, 'months').format('YYYY-MM'); const nextMont = moment(currentDate).add(1, 'months').format('YYYY-MM'); const currMont = moment(currentDate).format('YYYY-MM'); const month = preMont + ',' + currMont + ',' + nextMont; return { beginDate, endDate, preMont, nextMont, currMont, month }; }
2.工具類函數
/** * 正則表達式獲取地址欄參數 */ export const getURLParameters = (url) => { url = url.split('?')[1] || ''; url = url.split('&'); return url.reduce((total, item) => { let itemArr = item.split('='); total[itemArr[0]] = itemArr[1]; return total; }, {}); }; /** * filter過濾 */ const filterArr = (scheduleByDay[currentDate] || []).filter(v => { return v.status !== 4; }); const tagData = Object.keys(tagDataByMonth).map((key) => { const obj = tagDataByMonth[key][0]; const scheduleByDayItem = scheduleByDay[key] || []; return { date: key, tag: scheduleByDayItem.length === 1 ? scheduleByDayItem[0].userDesc : obj.displayDesc, tagColor: obj.showType === '1' ? '#F5A623' : '#CCCCCC' }; }); let scheduleIdArray = Object.keys(curScheduleMonth).map(v => curScheduleMonth[v]).reduce((total, item) => { total = [...total, ...item]; return total; }, []); let scheduleId = scheduleIdArray.length ? scheduleIdArray[0].scheduleId : null; let isOnlyOne = scheduleId ? scheduleIdArray.every(v => v.scheduleId === scheduleId) : false; /** * 獲取服務端時間 */ getServerTimeAsync() { return new Promise((resolve) => { try { my.call('getServerTime', (res) => { resolve(res.time); }); } catch (e) { resolve(new Date().getTime()); } }); }, /** * 檢查文本域的長度 * @param keyword * @returns {*} */ checkKeywordLength(keyword) { const { maxlength } = this.data; if (keyword.length > maxlength) { keyword = keyword.substring(0, maxlength); } return keyword; }, const { data: { items: initEvaluateItems } } = serviceKey; const initItems = initEvaluateItems.map(item => { const { score, id, itemName, levelDesc, maxLevel } = item; return { score, id, itemName, levelDesc, maxLevel }; });
3.層級較深的數據結構
{ "success": true, "value": { "merchant": { "id": 0, #物理id "partakerId": 0, "partakerName": "string", "merchantPid": "string", "merchantName": "string", "owners": { "guarantee_owner":[{"account":"string","name":"string"}], }, #負責人 }, "extension":{ keyValues: { channel:{ key:{ id:"21", creator:"流年", dataSource:"", key:"duration", label:"項目週期", type:"date", isRequire:"Y" }, value:"2018-06-02 17:55:12" }, is_sign:{ key:{ id:"32", creator:"lily", dataSource:"[{'key':'current','value':'今天'},{'key':'last','value':'昨天'}]", key:"startTime", label:"啓動時間", type:"select", isRequire:"N" }, value:"last" }, merchantInfo:{ key:{ id:"02", creator:"jack", dataSource:"", key:"taskCount", label:"任務量", type:"number", isRequire:"Y" }, value:"55" }, code:"DEFAULT", tempName:"社區服務" } }, #動態字段 }, "msg": "string", #錯誤信息 "code": "string" #錯誤碼 } const { stat, value = {}, msg } = response || {}; if (stat === 'fail') { message.error(msg); } const { merchant = {}, extension = {} } = value; const { keyValues = {} } = extension; const extenData = Object.entries(keyValues).map(v => { const [arr1, arr2] = v; const { key, recordId, value: newValue } = arr2; return { key, value: newValue, recordId }; }); console.log('動態數據-----', extenData); const linksObj = { 活動信息: links.slice(0, 2), 活動商戶信息: links.slice(2, 8), 保障商戶信息: links.slice(8), }; getFormDataDom = (data) => { const { getFieldDecorator } = this.props.form; const { formItem = {} } = this.props; return data.map((val) => { const { name, id, isSelect = false, isSelectInputOwners = false, isInput = false } = val; let isSimpleInitial; let isSelectInputOwnersInitial; if (isSelect || isInput) { isSimpleInitial = formItem && formItem[id] ? formItem[id] : ''; } if (isSelectInputOwners) { isSelectInputOwnersInitial = formItem && formItem[id] && formItem[id].length > 0 ? formItem[id].map(v => v.name) : []; } const initialValue = isSelectInputOwners ? isSelectInputOwnersInitial : isSelect || isInput ? isSimpleInitial : ''; return ( <Col span={12} key={id}> <FormItem label={name} {...formItemLayout}> {getFieldDecorator(`${id}`, { initialValue })(this.getFormItem(formItem, val)) } </FormItem> </Col> ); }); }; extenArr = (extenData = []) => { return extenData.map((item) => { const { key, value } = item; const { fieldKey, fieldLabel } = key; let { dataSource } = key; let spanValue = ''; if (dataSource === '') { spanValue = value; } else { try { dataSource = dataSource.replace(/'/img, '"'); const jsonValue = JSON.parse(dataSource); spanValue = jsonValue.reduce((total, i) => { total[i.key] = i.value; return total; }, {})[value]; } catch (e) { spanValue = ''; } } return { name: fieldLabel, id: fieldKey, spanValue }; }); }; <Form> <Row> { Object.entries(linksObj) .map((item, index) => { const [item1, item2] = item; return <div key={index}> <h3>{item1}</h3> <Row style={{ borderBottom: index === Object.entries(linksObj).length - 1 ? '1px dashed #ccc' : 'none' }}> { this.getFormDataDom(item2) } </Row> </div>; }) } { this.getFormDataDom(this.extenArr(extenData)) } </Row> </Form>