#javascript
Есть массив объектов вида: var data1 = [ { month:"Jan", category:"Final", value: "141" }, { month:"Jan", category:"Raw Material", value: "3 513" }, { month:"Jan", category:"Raw material class B", value: "1 551" }, { month:"Jan", category:"Scrap", value: "116" }, { month:"Jan", category:"Trading", value: "59" }, { month:"Jan", category:" ", value: " " }, { month:"Feb", category:"Final", value: "144" }, { month:"Feb", category:"Raw Material", value: "3 631" }, { month:"Feb", category:"Raw material class B", value: "1 591" }, { month:"Feb", category:"Scrap", value: "116" }, { month:"Feb", category:"Trading", value: "30" }, { month:"Feb", category:" ", value: " " }, ]; Каким образом его можно привести к виду: { category:"Final", value: [141, 144, ...] }, { category:"Raw Material", value: [3513,3631, ... ] }
Ответы
Ответ 1
var data1 = [ { month:"Jan", category:"Final", value: "141" }, { month:"Jan", category:"Raw Material", value: "3 513" }, { month:"Jan", category:"Raw material class B", value: "1 551" }, { month:"Jan", category:"Scrap", value: "116" }, { month:"Jan", category:"Trading", value: "59" }, { month:"Jan", category:" ", value: " " }, { month:"Feb", category:"Final", value: "144" }, { month:"Feb", category:"Raw Material", value: "3 631" }, { month:"Feb", category:"Raw material class B", value: "1 591" }, { month:"Feb", category:"Scrap", value: "116" }, { month:"Feb", category:"Trading", value: "30" }, { month:"Feb", category:" ", value: " " }, ]; console.log(data1.reduce((result, {category, value}) => { let target = result.find(row => row.category == category); if(!target) { target = {category, values: []}; result.push(target); }; target.values.push(value); return result; }, []));
Комментариев нет:
Отправить комментарий