我下面有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,
…
}
]
答案 0 :(得分:1)
您需要做的是:
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);
答案 1 :(得分:0)
使用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;
});