【问题标题】:Sum values in a Array of JavaScript deep Objects对 JavaScript 深层对象数组中的值求和
【发布时间】:2018-06-22 01:51:12
【问题描述】:

我一直在寻找解决方案并尝试不同的方法来获得我正在寻找的解决方案几个小时。我在下面有一个数组,我希望能够分别对数组做两件事。 (所以两个独立的功能)

功能 1. 我想对所有“权重”值求和。 (即 3 + 2 + 1 + 2 + 1 + 1 + 0)我尝试使用 lodash sumBy ,它在对数组中的简单对象求和方面做得很好。

功能 2。我希望能够遍历元素(我一直在尝试使用 lodash 将对象展平,但没有成功。)

我正在寻求任何帮助。如果这是一个新手问题,或者它的问题已经解决,我很抱歉,由于某种原因我找不到正确的搜索词。

编辑: 目前使用的是es5,所以箭头功能不可用

var answers = [{
    '1': {
      id: '5aa2542e4e31482f1e',
      text: 'Employee',
      orderNo: 2,
      weight: 3,
    },
    '5': {
      id: '5a442e47339482f22',
      text: 'Worker',
      orderNo: 6,
      weight: 2,
    }
  },
  {
    '2': {
      id: '5a52442e4739482f51',
      text: 'Time Sensive',
      orderNo: 3,
      weight: 1,
    },
    '3': {
      id: '5a2442e47e3932f52',
      text: 'Group Sensitive',
      orderNo: 4,
      weight: 2,
    }
  },
  {
    id: '5a57d9375a5a7ac20317',
    text: 'Med',
    orderNo: 1,
    weight: 1
  },
  {
    id: '5a57da0755a7ac4691c',
    text: 'Med ',
    orderNo: 2,
    weight: 1
  },
  {
    id: '5a57da545aa7ac206220',
    text: 'Yes',
    orderNo: 1,
    weight: 0
  }
]
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

【问题讨论】:

  • ...为什么该数组中有两种不同的数据格式?
  • 这些来自发送给我的调查的答案。顶部来自复选框的问题,因此用户可以选择多个元素。底部是只有一个答案的收音机。
  • EDIT: Currently using es5, so arrow functions are not available (Yet). Es5 永远不会包含箭头函数,因为规范已经完成。您可以使用 function () 代替
  • 我不是说 es5,我的意思是更新我的代码以使用 es6。

标签: javascript lodash


【解决方案1】:

基本的解决方案是展平你的数组

const x = answers.map(obj => Object.values(obj))

之后你有一个数组数组

您可以使用 reduce 加入这些数组。

const flattenedAnswers = x.reduce((acc, item) => acc.concat(item), []);

要对权重求和,可以使用 map 和 reduce

const sum = flattenedAnswers.map(item => item.weigt).reduce((acc, item) => acc + item), 0);

要遍历项目,只需遍历展平的答案数组

var answers = [{
    '1': {
      id: '5aa2542e4e31482f1e',
      text: 'Employee',
      orderNo: 2,
      weight: 3,
    },
    '5': {
      id: '5a442e47339482f22',
      text: 'Worker',
      orderNo: 6,
      weight: 2,
    }
  },
  {
    '2': {
      id: '5a52442e4739482f51',
      text: 'Time Sensive',
      orderNo: 3,
      weight: 1,
    },
    '3': {
      id: '5a2442e47e3932f52',
      text: 'Group Sensitive',
      orderNo: 4,
      weight: 2
    }
  }
]

const flat = answers.map(x => Object.values(x)).reduce((acc, item) => acc.concat(item), []);

const sum = flat.map(x => x.weight).reduce((acc, item) => acc + item, 0);

console.log(sum)

【讨论】:

    【解决方案2】:

    可以通过answers.forEach(answer => {...})迭代数组元素

    您可以通过Object.keys(answer).forEach(key => {let val = answer[key]})迭代答案属性

    在每个answer 和 中查找每个val 中的Weight 属性,如果存在,请将其添加到您在foreach 之外定义的变量中功能。

    【讨论】:

      猜你喜欢
      • 2017-08-23
      • 1970-01-01
      • 2020-04-13
      • 2016-09-05
      • 2021-08-09
      • 2019-02-03
      • 1970-01-01
      • 2021-11-26
      • 2013-10-14
      相关资源
      最近更新 更多