首页 > 解决方案 > 如何在Javascript中从两个不同的数组计算和创建新的对象值

问题描述

var array1 = [{issueCount: 16, failCount: 38, id: 1},
{issueCount: 15, failCount: 37, id: 2},
{issueCount: 15, failCount: 34, id: 3}];

var array2 = [{id: 1, totalAttempts: 57},
{id: 2, totalAttempts: 59},
{id: 3, totalAttempts: 67},
{id: 4, totalAttempts: 59}];

我有两个数组。从上面的数组中,我需要使用 (array1.fail count/array2.totalAttempts) * 100 [id is common between two arrays]来计算失败百分比。最终的数组需要以下格式。

outputArray = [{id: 1, issueCount: 16, failCount: 38, percentage: 66.66},
{id: 2, issueCount: 15, failCount: 37, percentage: 62.71},
{id: 3, issueCount: 15, failCount: 34, percentage: 50.74}];

提前致谢。

标签: javascriptarraysjavascript-objects

解决方案


您可以通过一个简单的 for 循环来实现这一点。

只需检查第二个数组中是否存在 id,如果存在,请进行计算。

const array1 = [{issueCount: 16, failCount: 38, id: 1},
{issueCount: 15, failCount: 37, id: 2},
{issueCount: 15, failCount: 34, id: 3}];

const array2 = [{id: 1, totalAttempts: 57},
{id: 2, totalAttempts: 59},
{id: 3, totalAttempts: 67},
{id: 4, totalAttempts: 59}];

const outputArray = [];

array1.forEach(i1 => {
  const i2 = array2.find(i => i.id === i1.id);
  if(i2) {
    outputArray.push({
      id: i1.id, 
      issueCount: i1.issueCount, 
      failCount: i1.failCount,
      percentage: (i1.failCount / i2.totalAttempts) * 100
      }); 
  }
});
console.log(outputArray)


推荐阅读