[英]How to update the values in an Object with results from an array
我有一个数据结构问题,我一直在尝试在 nodejs 中解决,但这给了我一个困难的时期,我将不胜感激。
我有一个 object:
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()
迭代您的 arrays 之一,对于每次迭代,您可以使用当前索引从另一个数组中获取关联值(这作为第二个参数传递给您的.map()
回调)。 对于回调的每次调用,您都可以返回所需obj
形状的新 object,每个属性设置如下:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.