繁体   English   中英

从另一个对象数组创建一个对象数组,并为其添加更多属性

[英]Create an array of objects from another array of objects and add more properties to it

我有一个对象数组,想要向该对象添加额外的属性并获取新的对象数组

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'));
    })

但这似乎不起作用。 什么是实现这一目标的最佳方法?

您需要使用... 传播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) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM