簡體   English   中英

Javascript根據鍵和值比較2個對象數組

[英]Javascript Compare 2 array of object based on key and value

我下面有 2 個對象數組。 我想比較兩者並檢查匹配的 random_code 並根據匹配的隨機代碼獲得分數。 我在下面提供了示例結果。 謝謝

me.records.data1(對象數組)

[
        {
            id: 345,
            user: 223,
            random_code: "50-3910111611011",
            created_at: "2019-03-01",
            is_verified: false,
            …
        }   1:{
        id: 346,
            user:223,
                random_code:"50-101966854102",
                    created_at:"2019-03-01",
                        is_verified:false,
      …
   }
]

me.records.data2(對象數組)

[  
   {  
      id:161,
      questionaire_content:80,
      questionaire_content_choice:272,
      created_at:"2019-03-01",
      random_code:"50-3910111611011",
      score:"0",
      …
   }   1:{  
      id:162,
      questionaire_content:79,
      questionaire_content_choice:270,
      created_at:"2019-03-01",
      random_code:"50-101966854102",
      score:"1",
      …
   }
]

根據上面的數據,結果應該是這樣的。

]{  
id:345,
user:223,
random_code:"50-3910111611011",
created_at:"2019-03-01",
score:0,
is_verified:false,
…
}{  
id:346,
user:223,
random_code:"50-101966854102",
created_at:"2019-03-01",
score:1,
is_verified:false,
…
}

]

使用 forEach 循環遍歷 me.records.data1,並匹配 me.records.data2 中的 random_code。 當 random_code 匹配時,將 data2.score 分配給 me.records.data1。

me.records.data1.forEach(function(obj){  
    var bscore = ""; 
    data2 = me.records.data2.find(function(i) { if(i.random_code === obj.random_code) return i.score; });
    if(bscore!="") obj.score = data2.score;
});

你需要做的是:

  1. 迭代源數組。
  2. 對於源數組中的每一項,獲取對象的“random_code”鍵,並將值存儲在一個臨時變量中。
  3. 從scores數組中,找到一個“random_code”與存儲在臨時變量中的對象相匹配的對象,如果找到,則返回“score”鍵的值。

 const source = [ { id: 345, user: 223, random_code: "50-3910111611011", created_at: "2019-03-01", is_verified: false, }, { id: 346, user:223, random_code:"50-101966854102", created_at:"2019-03-01", is_verified:false, } ]; const scores = [ { id:161, questionaire_content:80, questionaire_content_choice:272, created_at:"2019-03-01", random_code:"50-3910111611011", score:"0", }, { id:162, questionaire_content:79, questionaire_content_choice:270, created_at:"2019-03-01", random_code:"50-101966854102", score:"1", } ]; // function to get the value of score key from scores array for matching random code. const getScoreForRandomCode = (randomCode) => { for (let index = 0; index < scores.length; index++) { const tempScore = scores[index]; if (tempScore.random_code === randomCode) { return tempScore.score; } } } const result = source.map ((item) => { const randomCode = item.random_code; const score = getScoreForRandomCode (randomCode); return { ...item, score: score || 'NA' }; }); console.log (result);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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