Javascript根据键和值比较2对象数组

时间:2019-03-01 04:26:59

标签: javascript arrays compare

我下面有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,
…
}

]

2 个答案:

答案 0 :(得分:1)

您需要做的是:

  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);

答案 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;
});