首页 > 解决方案 > 如何使用数组的结果更新对象中的值

问题描述

我有一个数据结构问题,我一直在尝试在 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()

标签: javascriptnode.js

解决方案


您可以使用 迭代您的一个数组.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);


推荐阅读