使用 angular 6 从对象数组中获取百分比

get percentage fro array of objects using angular 6

我想获取特定对象的百分比,例如: 我有一个选项数组:-

options: Array(2)
0: {id: 1, choice: "Yes", answer_count: 1}
1: {id: 2, choice: "No", answer_count: 0}

或mcq数组:-

options: Array(4)
0: {id: 1, choice: "Yes, of course", answer_count: 0}
1: {id: 2, choice: "There is not an immediate need in the product, I a…d it to get a basic understanding of the subject.", answer_count: 1}
2: {id: 3, choice: "This will help me to pursue my learning goal.", answer_count: 0}
3: {id: 4, choice: "No,  I am not sure if it was helpful enough", answer_count: 0}

我需要从 answer_count key 的总数中得到 choice key 的百分比 喜欢:choice: "Yes, ofcourse" 来自 answer count of choice: "Yes, ofcourse" to the total of all answer count in options

的百分比

谁能帮我找到这个问题的解决方案

您可以获得 answer_count 属性 的数组:

choices.map(function(item) {
    return item['answer_count']
})

然后您可以减少该数组以获得如下答案的数量:

choices.map(function(item) {return item['answer_count']}).reduce(function (a, b) { 
    return (a + b)
});

最后,用answer_count除以金额再乘以100得到百分比:

(item['answer_count'] / totalAnswers) * 100

使用您提供的数据:

let choices = [
  {id: 1, choice: "Yes, of course", answer_count: 0},
  {id: 2, choice: "There is not an immediate need in the product, I a…d it to get a basic understanding of the subject.", answer_count: 1},
  {id: 3, choice: "This will help me to pursue my learning goal.", answer_count: 0},
  {id: 4, choice: "No,  I am not sure if it was helpful enough", answer_count: 0}
];

let totalAnswers = choices.map(function(item) {return item['answer_count']}).reduce(function (a, b) { 
  return (a + b)
});

let percentages = choices.map(function (item) {
  return {
    'id': item['id'],
    'choice': item['choice'], 
    'percentage': (item['answer_count'] / totalAnswers) * 100
  }
})

console.log(percentages);