Возникли проблемы со сглаживанием некоторых вложенных данных - PullRequest
1 голос
/ 11 июля 2020

У меня есть некоторые данные, подобные показанным ниже, я хотел получить сумму всех положительных, отрицательных и нейтральных для типа ученика, поэтому я применил метод d3.nest, в котором я использовал ключ как ученик, и вернул сумму указанного значения.

{Type: student, positive: 2, negative: 1, neutral:0}, {Type: student, positive: 1, negative: 1, neutral:0}, {Type: student, positive: 1, negative: 1, neutral:0}, {Type: student, positive: 1, negative: 2, neutral:0} 

Это результат этого d3.nest, в операторе возврата .rollup я указал имя значения, подобное этому positive: d3.sum(d,function(f){ return f.positive;}) et c. Результат ниже.

`key: "student"
     value: {positive: 5, negative: 5, neutral: 0}`

Однако, чтобы построить радарный график, мне нужно сгладить данные, чтобы они были на один уровень, как показано ниже, но я не могу понять, как это сделать. Я пробовал делать это как в приведенном ниже коде, но продолжал получать ошибки, пожалуйста, не могли бы вы помочь.

{student: student, positive:5, negative:5, neutral:0}

Я пробовал это для каждого l oop, и это не сработало

var flatData = []
            subStudent.forEach(function(sub){
                sub.value(function(subval){
                    flatData.push({
                        level: sub.key,
                        value: subval.value
                    });
                });
            });
            console.log(JSON.stringify(flatData))

1 Ответ

0 голосов
/ 13 июля 2020

Возможно, на самом деле не нужен d3.nest(), если у вас нет причины?

Вы можете сделать это с помощью reduce (но я также включу пример d3.nest() ниже):

const input = [
  {Type: 'student', positive: 2, negative: 1, neutral:0},
  {Type: 'student', positive: 1, negative: 1, neutral:0},
  {Type: 'student', positive: 1, negative: 1, neutral:0},
  {Type: 'student', positive: 1, negative: 2, neutral:0},
  {Type: 'other', positive: 2, negative: 0, neutral:1},
  {Type: 'other', positive: 1, negative: 1, neutral:0},
  {Type: 'other', positive: 1, negative: 1, neutral:0}
];

const output = Object.values(input.reduce((aggObj, item) => {
  
  if (!aggObj.hasOwnProperty(item.Type)) aggObj[item.Type] = item;
  else {
    for (let key in item){
      if (key != "Type") aggObj[item.Type][key] += item[key];
    } 
  }
  return aggObj
}, {}))

console.log(output)

Ввод:

[
  { Type: 'student', positive: 2, negative: 1, neutral:0 },
  { Type: 'student', positive: 1, negative: 1, neutral:0 },
  { Type: 'student', positive: 1, negative: 1, neutral:0 },
  { Type: 'student', positive: 1, negative: 2, neutral:0 },
  { Type: 'other',   positive: 2, negative: 0, neutral:1 },
  { Type: 'other',   positive: 1, negative: 1, neutral:0 },
  { Type: 'other',   positive: 1, negative: 1, neutral:0 }
]

Выход:

[
  { Type: "student", positive: 5, negative: 5, neutral: 0 },
  { Type: "other",   positive: 4, negative: 2, neutral: 1 }
]

Если вам нужно / хотите d3.nest() вы можете сделать это (тот же ввод и вывод):

const input = [
  {Type: 'student', positive: 2, negative: 1, neutral:0},
  {Type: 'student', positive: 1, negative: 1, neutral:0},
  {Type: 'student', positive: 1, negative: 1, neutral:0},
  {Type: 'student', positive: 1, negative: 2, neutral:0},
  {Type: 'other', positive: 2, negative: 0, neutral:1},
  {Type: 'other', positive: 1, negative: 1, neutral:0},
  {Type: 'other', positive: 1, negative: 1, neutral:0}
];

const nested = d3.nest()
  .key(d => d.Type)
  .rollup(d => ({
    positive: d3.sum(d, f => f.positive),
    negative: d3.sum(d, f => f.negative),
    neutral: d3.sum(d, f => f.neutral),
  }))  
  .entries(input)
  
const output = nested.map(item => {
  //console.log(item)
  return {Type: item.key, ...item.value}
})

console.log(output)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...