數組我有這樣的:JS轉換嵌套對象爲對象
var dataSet = {
data: {
department: [
{
"Marketing": [
{ "employee_1": "1210" },
{ "employee_2": "3241" },
{ "employee_3": "6510" },
{ "employee_4": "9510" }
]
},
{
"Sales": [
{ "employee_1": "5210" },
{ "employee_2": "1241" },
{ "employee_3": "8510" },
{ "employee_4": "2510" }
]
},
{
"RD": [
{ "employee_1": "1010" },
{ "employee_2": "9241" },
{ "employee_3": "9430" },
{ "employee_4": "3510" }
]
},
...
]
}
}
我需要這樣的:
const data = [
{name: 'Marketing', Low: 2, Medium: 4, High: 3},
{name: 'Sales', Low: 3, Medium: 1, High: 5},
{name: 'RD', Low: 6, Medium: 1, High: 2},
...
];
其中:
LOW employee_x < 2000
MEDIUM employee_x >= 2000 && employee_x < 5000
HIGH employee_x >= 5000
我最後的嘗試是這樣的:
var low_arr_dept = [];
var medium_arr_dept = [];
var high_arr_dept = [];
for (var i in dataSet.data) {
var department = departments_data[i];
for (var d in department) {
var score = department[d];
for (var j in score) {
if (Object.values(department[d][j]) >= 5000) {
console.log("Object.values(department[d][j]) ", Object.values(department[d][j]))
low_arr_dept.push({
score: Object.values(department[d][j])
});
} else if (Object.values(department[d][j]) >= 2000 && Object.values(department[d][j]) < 5000) {
medium_arr_dept.push({
score: Object.values(department[d][j])
});
} else if (Object.values(department[d][j]) <2000) {
high_arr_dept.push({
score: Object.values(department[d][j])
});
}
}
}
}
// Creating arrays and then getting their length
low_arr_dept_marketing.length.toString()
medium_arr_dept_marketing.length.toString()
high_arr_dept_marketing.length.toString()
// For creating this:
const data = [
{name: 'Marketing', Low: low_arr_dept_marketing.length, Medium: medium_arr_dept_marketing.length, High: high_arr_dept_marketing.length},
{name: 'Sales', Low: low_arr_dept_sales.length, Medium: medium_arr_dept_sales.length, High: high_arr_dept_sales.length},
{name: 'RD'Low: low_arr_dept_rd.length, Medium: medium_arr_dept_rd.length, High: high_arr_dept_rd.length},
...
];
什麼是你目前執行的問題? –
我會推薦使用'reduce'。 – evolutionxbox
我不知道如何通過dataSet,並獲得每個部門分開的數組(高,中,低)。在我的一次嘗試中,我只獲得了聚合數組(所有部門在一起)。 – Dubliner