我有一个对象数组,想为该对象添加额外的属性并获取新的对象数组
const notificationList = [
{
id: 1,
primary: 'Item1',
secondary: 'Desc1',
date: 'Jan 2, 2019'
},
{
id: 2,
primary: 'Item2',
secondary: 'Desc2',
date: 'Jan 10, 2019'
},
{
id: 3,
primary: 'Item3',
secondary: 'Desc3',
date: 'Dec 9, 2018'
},
];
我需要获得以下列表
const notificationNewList = [
{
id: 1,
icon: <Icon1 />,
color: 'error',
primary: 'Item1',
secondary: 'Desc1',
date: 'Jan 2, 2019'
},
{
id: 2,
icon: <Icon2 />,
color: 'primary',
primary: 'Item2',
secondary: 'Desc2',
date: 'Jan 10, 2019'
},
{
id: 3,
icon: <Icon3 />,
color: 'secondary',
primary: 'Item3',
secondary: 'Desc3',
date: 'Dec 9, 2018'
},
];
const notificationsNewList = notificationList && notificationList.map(data => {
data.icon = (data.id === '1' ? <Icon1 /> : (data.id === '2' ? <Icon2 /> : <Icon3 />));
data.color = (data.id === '1' ? 'error' : (data.id === '2' ? 'primary' : 'secondary'));
})
但这似乎不起作用。实现此目标的最佳方法是什么?
答案 0 :(得分:1)
您需要使用...
spread 或Object.assign
function getIconJSX(data) => (data.id == 1 && <Icon1/>) || (data.id == 2 && <Icon2/>) || (data.id == 3 && <Icon3/>)
const notificationList = [
{
id: 1,
primary: 'Item1',
secondary: 'Desc1',
date: 'Jan 2, 2019'
},
{
id: 2,
primary: 'Item2',
secondary: 'Desc2',
date: 'Jan 10, 2019'
},
{
id: 3,
primary: 'Item3',
secondary: 'Desc3',
date: 'Dec 9, 2018'
},
];
const newNotificationList = notificationList.map(x => ({...x, Icon: getIconJSX(x)}))
console.log(newNotificationList)