我有任務對象的數組,我想通過ownerID
變換對象的平板陣列到嵌套對象
var tasks = [
{taskID: "1", title: "task1", ownerID: "100", ownerName: "John", allocation: 80},
{taskID: "2", title: "task2", ownerID: "110", ownerName: "Sarah", allocation: 50},
{taskID: "3", title: "task3", ownerID: "110", ownerName: "Sarah", allocation: 50},
{taskID: "4", title: "task4", ownerID: "120", ownerName: "Mike", allocation: 25},
{taskID: "5", title: "task5", ownerID: "120", ownerName: "Mike", allocation: 45}];
將這些轉化爲分組多維對象這是我期望的輸出:
var people = {
100: { ownerName: "John",
tasks: {
{taskID: "1", title: "task1", allocation: 80}
}
},
110: { ownerName: "Sarah",
tasks: {
{taskID: "2", title: "task2", allocation: 50}
{taskID: "3", title: "task3", allocation: 50}
}
},
120: { ownerName: "Mike",
tasks: {
{taskID: "4", title: "task4", allocation: 25}
{taskID: "5", title: "task5", allocation: 45}
}
},
};
我正在循環訪問原始數據並分配每行
people[ownerID] = {};
person = people[ownerID];
person['ownerName'] = ownerName;
person['tasks'] = {};
person[taskID] = {};
task = person[taskId];
task['taskID'] = taskID;
這似乎是由ownerID
罰款並創建一個嵌套的任務對象,但它只會爲每個人添加一個任務。
Argh。任何幫助真的很感激。
'tasks'應該是一個陣列,而不是一個對象。 –
@NinaScholz爲什麼?如果他們是一個數組,我仍然可以使用人[100] .tasks [3] .title訪問各個任務嗎? – ginsberg
我在想,你正在使用哪種數據類型。以上不是一個有效的例子。如果您需要反映'taskID'的屬性,那麼您還需要在示例中使用它。 –