目标需求:
添加零食种类
这是一个数组,里面包含很多对象,每个对象里面含有相同的属性
首先把想要的字段通过工具函数库lodash_.pick()出来:
let b = [];
classifylist.map( it => {
b.push(_.pick(it,'uuid','name'));
});
现在把数组转换成对象:
方法一:map循环方式
let obj = {};
b.map((e) => {
obj[e.uuid] = e.name;
});
方法二:$.each循环方式
$.each(b, function (item,e) {
console.log(e.name);
obj[e.uuid] = e.name;
});
方法三:for in 循环方式
for (var item in b){
obj[b[item].uuid] = b[item].name;
};
在table表格的columns中使用:
通过给obj对象传入键,返回值即可如愿以偿地展示了种类uuid对应的种类名称。
{
title: '零食种类',
dataIndex: 'classify_uuid',
render: it => (
{obj[it]}
),
},
columns完整代码如下:
import React, { Fragment } from 'react';
import _ from 'lodash';
import { Icon,Popconfirm } from 'antd';
import moment from 'moment';
export const DATE_TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss';
export const DATE_FORMAT = 'YYYY-MM-DD';
function getDateTimeString(msTimeOrDate) {
if (msTimeOrDate === null) return null;
if (msTimeOrDate && typeof msTimeOrDate === 'object') {
if ('format' in msTimeOrDate && typeof msTimeOrDate.format === 'function')
return msTimeOrDate.format(DATE_TIME_FORMAT);
if (msTimeOrDate instanceof Date) return moment(msTimeOrDate).format(DATE_TIME_FORMAT);
}
// @ts-ignore
return moment(new Date(msTimeOrDate)).format(DATE_TIME_FORMAT);
}
function newColumn(title, dataIndex, render = undefined ) {
return { title, dataIndex, render, key: dataIndex };
}
function getSnackColumns(props, eventHandler) {
const { snacks } = props;
const classifylist = Array.isArray(snacks.classifylist) ? snacks.classifylist : [];
console.warn('classifylist',classifylist);
let b = [];
let obj = {};
classifylist.map( it => {
b.push(_.pick(it,'uuid','name'));
});
b.map((e) => {
obj[e.uuid] = e.name;
});
console.warn('b', b);
console.warn('obj',obj);
return [
{
title: '零食照片',
dataIndex: 'images',
key: `uuid`,
render: src => src ? : '暂无照片'
},
newColumn('零食名称', 'name'),
// newColumn('零食分类uuid', 'classify_uuid'),
// 在这里使用
{
title: '零食种类',
dataIndex: 'classify_uuid',
render: it => (
{obj[it]}
),
},
newColumn('零食价格', 'money'),
{
title: '发布时间',
dataIndex: 'time',
defaultSortOrder: 'descend',
sorter: (a,b) => Date.parse(a.time) - Date.parse(b.time),
render: it => {
const m = moment(it);
return (
{m.fromNow()}
);
}
},
{
align: 'right',
title: '操作',
key: 'op',
render: it => {
return (
确认删除{it.name}吗?}
okType="danger"
onConfirm={eventHandler.onDeleteSnack.bind(null,it)}
okText="确认删除"
cancelText="取消"
>
删除
);
}
}
];
}
export default getSnackColumns;