我正在开发包含数据可视化的React应用程序。我需要使用javascript库或vanilla javascript来操作数据。这就是JSON数据的样子:
[
{
"respondent": "John",
"question 1": 1,
"question 2": 2,
"question 3": 7
},
{
"respondent": "Steve",
"question 1": 3,
"question 2": 4,
"question 3": 2
},
{
"respondent": "Jack",
"question 1": 5,
"question 2": 3,
"question 3": 6
},
{
"respondent": "Patricia",
"question 1": 4,
"question 2": 3,
"question 3": 4
},
{
"respondent": "Matt",
"question 1": 6,
"question 2": 2,
"question 3": 1
}
]
每个键都是问题文本。该值表示1到7之间的民意调查答案。
为了使其可视化,它需要看起来像这样:
const answers = [
{"question":"question 1", "answer":"1", "percent":0.09},
{"question":"question 1", "answer":"2", "percent":0.27},
{"question":"question 1", "answer":"3", "percent":0.59}
...
{"question":"question 3", "answer":"5", "percent":0.09},
{"question":"question 3", "answer":"6", "percent":0.27},
{"question":"question 3", "answer":"7", "percent":0.59}
]
所以我需要在每个问题中计算唯一值并将其转换为百分比。 100%=同一问题中的所有答案
您将如何进行此数据操作?以下是更大的数据集:https://pastebin.com/ZuyV8w6Z
答案 0 :(得分:1)
这是我提出的解决方案。
const surveyData = [...]
let cleanSurveyData = [];
//Get unique questions
const questions = _.chain(surveyData).map(_.keys).flatten().uniq().value();
//Iterate over each question
questions.forEach(function(questionTitle) {
//Grab data only containing selected question title
let mapSelectedData = _.map(surveyData, questionTitle)
//Count how many answers total
let answersTotal = mapSelectedData.length;
//Count how many times each number appears in the answer
mapSelectedData = _.countBy(mapSelectedData)
//possible answers are 1 to 7
const answerRange = _.range(1,8)
//iterate over possible answers
answerRange.forEach(function(selectedNumber) {
let element = {};
element.question = questionTitle;
element.answerNumber = selectedNumber;
//Get value from selectedNumber
let numVal = _(mapSelectedData).result(selectedNumber);
element.count = (isNaN(numVal) ? 0 : numVal)
element.pct = element.count / answersTotal;
cleanSurveyData.push(element);
})
console.log(cleanSurveyData)