JS将数组转化为对象obj:键值对形式{}⽬标需求:
添加零⾷种类
根据零⾷种类分配的UUID映射展⽰出来:
获取到零⾷种类的列表的数据结构是这样⼦的:
这是⼀个数组,⾥⾯包含很多对象,每个对象⾥⾯含有相同的属性
⾸先把想要的字段通过⼯具函数库lodash_.pick()出来:
let b = [];
classifylist.map( it => {
b.push(_.pick(it,'uuid','name'));
});
_.pick()完的数据结构是这样的:
现在把数组转换成对象:
⽅法⼀: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 => (
<span>{obj[it]}</span>
),
},
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_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
typeof arrayreturn 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 ? <img src={src} alt="logo" style={{width: '100%', maxWidth: 64}} /> : '暂⽆照⽚'        },
newColumn('零⾷名称', 'name'),
// newColumn('零⾷分类uuid', 'classify_uuid'),
// 在这⾥使⽤
{
title: '零⾷种类',
dataIndex: 'classify_uuid',
render: it => (
<span>{obj[it]}</span>
),
},
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 (
<span title={getDateTimeString(m)}>
{m.fromNow()}
</span>
);
}
},
{
{
align: 'right',
title: '操作',
key: 'op',
render: it => {
return (
<Fragment>
<Popconfirm
title={<span>确认删除<b>{it.name}</b>吗?</span>}                      okType="danger"
onConfirm={DeleteSnack.bind(null,it)}                      okText="确认删除"
cancelText="取消"
>
<a style={{ color: '#FC1E39', marginLeft: 20 }}>
<Icon type="delete" /> ;删除
</a>
</Popconfirm>
</Fragment>
);
}
}
];
}
export default getSnackColumns;

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。