javascript - 使用 es6 向对象插入新属性
问题描述
我想在对象数组中添加新对象
const valueObj = Object.keys(values);
const filterCompetencies = competencies.filter(item =>
item.competencies.find(i => !i.isComputational),
);
const filterComp = filterCompetencies.map(item => item.competencies);
const flatten = _.flattenDeep(filterComp);
const auditLogObj = flatten.map(item => ({
employeeId: _.toNumber(currentUserId),
actionName: `Updated target for ${item.name}`,
actionDate: dateToday,
actionBy: `${mentorSignature.firstName} ${mentorSignature.lastName}`,
}));
console.log(auditLogObj);
console.log(valueObj);
我希望我的对象插入新对象,它看起来像这样
{
employeeId: 243,
id: "target-3-0",
actionBy: "Sophia Vaughn",
actionDate: "Nov 14 2020 14:49:29 PM",
actionName: "Updated target for Mentorship (as mentee)"
},
{
employeeId: 243,
id: "target-3-1",
actionBy: "Sophia Vaughn",
actionDate: "Nov 14 2020 14:49:29 PM",
actionName: "Updated target for Continuous Learning"
},
{
employeeId: 243,
id: "target-3-2",
actionBy: "Sophia Vaughn",
actionDate: "Nov 14 2020 14:49:29 PM",
actionName: "Updated target for Certifications Passed"
},
...
解决方案
最简单的方法是扩充你的映射器,以便为它创建的每个新对象,从valueObj
索引中获取相应的 id:
const auditLogObj = flatten.map((item, i) => ({
id: values[i],
employeeId: _.toNumber(currentUserId),
actionName: `Updated target for ${item.name}`,
actionDate: dateToday,
actionBy: `${mentorSignature.firstName} ${mentorSignature.lastName}`,
}));
推荐阅读
- android - 设置包名称是否会显式隐含意图?
- firebase - 保护 Cloud Functions auth onDelete 触发器
- ios - iOS VoiceOver“找不到标题”
- java - 如何将 Enum 的值与 Enum 方法中 Enum 的所有可能值进行比较并避免丢失 return 语句?
- javascript - 如何将 Fuse.js 导入为 ES6 模块客户端?
- python - 来自 cormens 算法的最大子数组问题中的未绑定局部误差
- go - 运行时:当将结构保存到 json 时,goroutine 堆栈超过 1000000000 字节的限制
- java - 如何将带有“-i --upload-file”的 curl 调用转换为 java Unirest 或任何其他 http 请求?
- react-native - 使用 react native navigator 传递参数
- hive - Hive 3.1+ 不会反序列化来自 Kafka 1.0+ 的 Avro 1.8.3+ 消息