javascript - 从另一个对象数组创建一个对象数组并向其添加更多属性
问题描述
我有一个对象数组,想为对象添加额外的属性并获取新的对象数组
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)
推荐阅读
- javascript - 尝试导入错误:“configureStore”未从“./app/store”导出
- javascript - 如何在数组 Mongodb 中拆分 2 个对象
- php - 如何修复 MySQL 错误:您的 SQL 语法有错误
- sequelize.js - 嵌套包含未显示第二个包含的数据
- pine-script - 松脚本趋势线获取当前价格问题
- swift - 是否有 SwiftUI“拖入”手势?
- javascript - 有没有办法使用 quick.db 制作 discord.js 日志系统
- javascript - 如何使用 useLocation 路由到新布局?
- json - 如何使用 jq 流模式为每个字典添加新密钥
- javascript - 动态地将属性绑定到类