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

Posted

技术标签:

【中文标题】使用角度 6 从对象数组中获取百分比【英文标题】:get percentage fro array of objects using angular 6 【发布时间】:2020-05-13 21:48:31 【问题描述】:

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

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 的百分比

谁能帮我解决这个问题

【问题讨论】:

【参考方案1】:

您可以通过以下方式获取 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);

【讨论】:

以上是关于使用角度 6 从对象数组中获取百分比的主要内容,如果未能解决你的问题,请参考以下文章

角度切片对象数组

如何使用角度获取数组中对象的索引?

如何在角度 6 中使用 @Output 来发出对象数组?

如何使用角度 7 从对象数组中返回 userPass 的值?

通过属性值从对象数组中获取JavaScript对象[重复]

通过属性值从对象数组中获取JavaScript对象[重复]