合并对象以获得数组中的平均值 [英] Merging objects to obtain the average value in arrays

查看:77
本文介绍了合并对象以获得数组中的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取分数数组的平均值,并从第一个对象保留其他值.我无法管理如何遍历对象以实现预期的输出.

I'm trying to obtain an average value for scores arrays and leave other values from the first object. I can't manage how to loop through the objects to achieve expected output.

const bigArr = [
  {
    bigDummyData: "string0",
    examples: [
      { smallDD: "string00", scores: [1, 1, 5] },
      { smallDD: "string01", scores: [2, 2, 4] },
      { smallDD: "string02", scores: [2, 2, 6] },
    ],
  },
  {
    bigDummyData: "string1",
    examples: [
      { smallDD: "string10", scores: [3, 3, 3] },
      { smallDD: "string11", scores: [2, 2, 2] },
      { smallDD: "string12", scores: [4, 4, 4] },
    ],
  },
]

预期输出:

output = {
    bigDummyData: "string0",
    examples: [
      { smallDD: "string00", scores: [2, 2, 4] },
      { smallDD: "string01", scores: [2, 2, 3] },
      { smallDD: "string02", scores: [3, 3, 5] },
    ],
  }

如您所见,bigDummyData和每个smallDD都位于第一个对象的左边.

As you can see, bigDummyData and each smallDD are left from the first object.

这是问题的简化示例 bigArr examples 数组是动态上传的,因此通常要长得多.

That's is a simplified example of the problem, arrays bigArr and examples are uploaded dynamically, so they are usually much longer.

推荐答案

可能会帮助您

const bigArr = [
  {
    bigDummyData: "string0",
    examples: [
      { smallDD: "string00", scores: [1, 1, 5] },
      { smallDD: "string01", scores: [2, 2, 4] },
      { smallDD: "string02", scores: [2, 2, 6] },
    ],
  },
  {
    bigDummyData: "string1",
    examples: [
      { smallDD: "string10", scores: [3, 3, 3] },
      { smallDD: "string11", scores: [2, 2, 2] },
      { smallDD: "string12", scores: [4, 4, 4] },
    ],
  }
]

let firstElement = bigArr[0];
let length = bigArr.length;
bigArr.splice(0,1)

bigArr.forEach(({examples}) => {
  examples.forEach(({scores},i) => {
    firstElement.examples[i].scores = firstElement.examples[i].scores.map( (x,j) => x+scores[j]); 
  })
});

  firstElement.examples.forEach(({scores},i) => {
    firstElement.examples[i].scores = firstElement.examples[i].scores.map( (x) => x/length); 
  });
console.log(firstElement);

何时使用地图

基于在现有阵列中执行的某些操作来创建新阵列.官方文档

Creating new array based on doing some operation in existing array.Official Documentation

拼接

splice()方法通过删除或替换现有元素和/或添加新元素来更改数组的内容

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements Official Documentation

如果可以的话,请接受.

Accept this,if it helps you.

这篇关于合并对象以获得数组中的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆