前端对于数据的处理一般会用到foreach、map、reduce、Object.values()、Object.keys()、Object.entries()等方法,下面逐次进行分析
foreach
forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。foreach方法不会返回执行结果。
注意: forEach() 对于空数组是不会执行回调函数的。foreach会改变原数组。
语法:
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() 不会对空数组进行检测。
注意: 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。
注意: reduce() 对于空数组是不会执行回调函数的。
语法:
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>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。