首页 > 解决方案 > 从另一个对象数组创建一个对象数组并向其添加更多属性

问题描述

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

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

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

标签: javascriptreactjs

解决方案


您需要使用... 价差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)


推荐阅读