отделить вложенный массив в javascript?

#javascript

#javascript

Вопрос:

У меня есть массив данных в приведенном ниже формате

 output = [
  {
    tasks: [
      {
        chartType: "bar",
        code: "p1",
        showInReport: true,
        value: 2827.5
      },
      {
        chartType: "line",
        code: "p2",
        showInReport: true,
        value: 4394
      },
      {
        chartType: "pie",
        code: "p3",
        showInReport: true,
        value: 10975
      }
    ],
    time: "2020-07"
  },
  {
    tasks: [
      {
        chartType: "bar",
        code: "p1",
        showInReport: true,
        value: 3720.5
      },
      {
        chartType: "line",
        code: "p2",
        showInReport: true,
        value: 6086.5
      },
      {
        chartType: "pie",
        code: "p3",
        showInReport: true,
        value: 8741
      }
    ],
    time: "2020-08"
  },
  {
    tasks: [
      {
        chartType: "bar",
        code: "p1",
        showInReport: true,
        value: 6110.5
      },
      {
        chartType: "line",
        code: "p2",
        showInReport: true,
        value: 8781
      },
      {
        chartType: "pie",
        code: "p3",
        showInReport: true,
        value: 13362
      }
    ],
    time: "2020-09"
  }
]
  

Я хочу разделить этот массив на два массива на основе chartType . Если chartType = "pie" отделить массив:

 pieData = [
  {
    tasks: [
      {
        chartType: "pie",
        code: "p3",
        showInReport: true,
        value: 10975
      }
    ],
    time: "2020-07"
  },
  {
    tasks: [
      {
        chartType: "pie",
        code: "p3",
        showInReport: true,
        value: 8741
      }
    ],
    time: "2020-08"
  },
  {
    tasks: [
      {
        chartType: "pie",
        code: "p3",
        showInReport: true,
        value: 13362
      }
    ],
    time: "2020-09"
  }
]
  

ещё

 barLineData = [
  {
    tasks: [
      {
        chartType: "bar",
        code: "p1",
        showInReport: true,
        value: 2827.5
      },
      {
        chartType: "line",
        code: "p2",
        showInReport: true,
        value: 4394
      }
    ],
    time: "2020-07"
  },
  {
    tasks: [
      {
        chartType: "bar",
        code: "p1",
        showInReport: true,
        value: 3720.5
      },
      {
        chartType: "line",
        code: "p2",
        showInReport: true,
        value: 6086.5
      }
    ],
    time: "2020-08"
  },
  {
    tasks: [
      {
        chartType: "bar",
        code: "p1",
        showInReport: true,
        value: 6110.5
      },
      {
        chartType: "line",
        code: "p2",
        showInReport: true,
        value: 8781
      }
    ],
    time: "2020-09"
  }
]
  

Мои знания js слабы, поэтому я не знаю, как это сделать.

Комментарии:

1. вы что-нибудь пробовали?

2. Array#filter твой друг здесь

Ответ №1:

Вы могли бы использовать filter для разделения объектов по типу диаграммы

 output = [ { tasks: [ { chartType: "bar", code: "p1", showInReport: true, value: 2827.5 }, { chartType: "line", code: "p2", showInReport: true, value: 4394 }, { chartType: "pie", code: "p3", showInReport: true, value: 10975 }, ], time: "2020-07", }, { tasks: [ { chartType: "bar", code: "p1", showInReport: true, value: 3720.5 }, { chartType: "line", code: "p2", showInReport: true, value: 6086.5 }, { chartType: "pie", code: "p3", showInReport: true, value: 8741 }, ], time: "2020-08", }, { tasks: [ { chartType: "bar", code: "p1", showInReport: true, value: 6110.5 }, { chartType: "line", code: "p2", showInReport: true, value: 8781 }, { chartType: "pie", code: "p3", showInReport: true, value: 13362 }, ], time: "2020-09", }, ];

let pie = [],
  nonPie = [];
output.forEach((o) => {
  nonPie.push({
    tasks: [
      ...o.tasks.filter((p) =>
        p.chartType == "pie"
          ? (pie.push({ tasks: [p], time: o.time }), false)
          : true
      ),
    ],
    time: o.time,
  });
});
console.log(pie);
console.log("-----------------------------");
console.dir(nonPie);  

Комментарии:

1. Что вы подразумеваете под кодом ? (pie.push({ tasks: [p], time: o.time }), false) : true Я не понимаю синтаксис true, false

2. это троичный оператор, он эквивалентен if (p.chartType == "pie") {pie.push({ tasks: [p], time: o.time }) return false} else return true сначала он проверяет условие, если выполнено, он помещает объект в круговой массив, в противном случае он возвращает объект, дайте мне знать, если у вас возникнут еще какие-либо вопросы

Ответ №2:

Используйте Array.prototype.reduce для уменьшения массива задач внутри, проверив свойство ChartType и добавив его в основной редуктор следующим.

 const output = [
  {
    tasks: [
      {
        chartType: "bar",
        code: "p1",
        showInReport: true,
        value: 2827.5
      },
      {
        chartType: "line",
        code: "p2",
        showInReport: true,
        value: 4394
      },
      {
        chartType: "pie",
        code: "p3",
        showInReport: true,
        value: 10975
      }
    ],
    time: "2020-07"
  },
  {
    tasks: [
      {
        chartType: "bar",
        code: "p1",
        showInReport: true,
        value: 3720.5
      },
      {
        chartType: "line",
        code: "p2",
        showInReport: true,
        value: 6086.5
      },
      {
        chartType: "pie",
        code: "p3",
        showInReport: true,
        value: 8741
      }
    ],
    time: "2020-08"
  },
  {
    tasks: [
      {
        chartType: "bar",
        code: "p1",
        showInReport: true,
        value: 6110.5
      },
      {
        chartType: "line",
        code: "p2",
        showInReport: true,
        value: 8781
      },
      {
        chartType: "pie",
        code: "p3",
        showInReport: true,
        value: 13362
      }
    ],
    time: "2020-09"
  }
];

const { pie, nonPie } = output.reduce((acc, { tasks, time }) => {
    const reducedObj = tasks.reduce((r, c) => {
        if (c.chartType === 'pie') {
            r.pieTasks.push(c);
        } else {
            r.nonPieTasks.push(c);
        }
        
        return r;
    }, { pieTasks: [], nonPieTasks: [] });
    
    acc.pie.push({
        time,
        tasks: reducedObj.pieTasks
    });
    acc.nonPie.push({
        time,
        tasks: reducedObj.nonPieTasks
    });
    return acc;
}, { pie: [], nonPie: [] });

console.log('Pie chart data', pie);
console.log('Non pie chart data', nonPie);