我有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,
…
}
]
您需要做的是:
- 迭代源数组。
- 对于源数组中的每个项目,获取对象的" Random_Code"键,然后将值存储在临时变量中。
- 从分数数组中,找到一个对象,其" Random_Code"匹配存储在临时变量中的对象,如果找到了,请返回"分数"密钥的值。
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);
使用for 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;
});