簡體   English   中英

如何使用數組的結果更新 Object 中的值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM