簡體   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