javascript - 如何使用数组的结果更新对象中的值
问题描述
我有一个数据结构问题,我一直在尝试在 nodejs 中解决,但这给了我一个困难的时期,我将不胜感激。
我有一个对象:
let obj = {
commenter: '',
comment: '',
numberOflikes: 0,
}
还有一个容器:
let container = []
我有一组评论和评论者,以及喜欢数量的值:
//total likes
let likes = 176;
// total commenters
const totalcommenters = [
'john doe1',
'john doe 2',
'john doe 3',
'john doe 4',
'john doe 5',
];
// total comments
const totalComment = [
'this is a comment one',
'this is a comment two',
'this is a comment three',
'this is a comment four',
'this is a comment five',
];
我想更新对象,并将它们放入容器中。这是我想要的结果:
[
{
commenter: 'john doe1',
comment: 'this is a comment one',
numberOflikes: 176,
},
{
commenter: 'john doe2',
comment: 'this is a comment two',
numberOflikes: 176,
},
{
commenter: 'john doe3',
comment: 'this is a comment three',
numberOflikes: 176,
},
{
commenter: 'john doe4',
comment: 'this is a comment four',
numberOflikes: 176,
},
{
commenter: 'john doe5',
comment: 'this is a comment five',
numberOflikes: 176,
}
]
但我没有得到想要的结果。这是我到目前为止所做的,我尝试以 OOP 方式处理它:
class Data {
// loop though and update comments
static updateComment() {
let mapFunc = (comment) => {
return { ...obj, comment: comment }
}
let mapped = totalComment.map(mapFunc)
}
static updateCommenters() {
let mapFunc = (commenter) => {
return { ...obj, commenter: commenter }
}
let mappedcommenters = totalcommenters.map(mapFunc)
}
}
Data.updateComment()
Data.updateCommenters()
解决方案
您可以使用 迭代您的一个数组.map()
,对于每次迭代,您可以使用当前索引从另一个数组中获取关联的值(这作为第二个参数传递给您的.map()
回调)。对于回调的每次调用,您可以返回所需obj
形状的新对象,每个属性设置如下:
const likes = 176;
const totalcommenters = [ 'john doe1', 'john doe 2', 'john doe 3', 'john doe 4', 'john doe 5', ];
const totalComment = [ 'this is a comment one', 'this is a comment two', 'this is a comment three', 'this is a comment four', 'this is a comment five', ];
const res = totalcommenters.map((commenter, i) => ({
commenter,
comment: totalComment[i],
numberOfLikes: likes
}));
console.log(res);
推荐阅读
- mongodb - 当 find()-Request 包含比较时如何定义多键索引
- c# - C# EWS 将收件箱中找到的所有电子邮件保存到项目列表中
- python - tkinter mainloop() 函数让我退出我的 mac
- c# - 一种将 System.Windows.Forms.DataVisualization.Charting 图表图像保存为 .svg 或其他矢量图像的方法
- wso2 - 启用第二个 wso2 Publisher/Store 实例
- spring-batch - Spring批处理ItemReader语言环境,用逗号导入双精度
- python - 如何在谷歌云功能上使用电报 webhook?
- python - 将数据帧拆分为 train_test 以输入 CNN
- amazon-web-services - 在我的免费等级账户中为未使用的弹性 IP 计费,即使我没有在我的账户中看到任何分配的弹性 IP
- android - Android CarrierMessagingService 收不到短信事件