![](/img/trans.png)
[英]How to compare array of object based on key and value and delete object
[英]Javascript Compare 2 array of object based on key and value
我下面有 2 個對象數組。 我想比較兩者並檢查匹配的 random_code 並根據匹配的隨機代碼獲得分數。 我在下面提供了示例結果。 謝謝
[
{
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;
});
你需要做的是:
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.