8. 數據分類

在遇到數據須要根據標題等進行分類:spa

//數據
let data = [
    {
        device_id: "AAAAAAA",
        filename: "Log_2019-04-09-00-00.tar",
    },
    {
        device_id: "AAAAAAA",
        filename: "Log_2019-04-09-00-01.tar",
    },
    {
        device_id: "BBBBBBB",
        filename: "Log_2019-04-09-00-02.tar",
    },
];

//分類
export function classifyLogList(data) {
    let newArr = [];
    data.map((oldData, i) => {
        let index = -1;
        let alreadyExists = newArr.some((newData, j) => {
            if (oldData.device_id === newData.device_id) {
                index = j;
                return true
            }
        })
        if (alreadyExists) {
            newArr[index].file_list.push(oldData.filename)
        } else {
            newArr.push({
                device_id: oldData.device_id,
                file_list: [oldData.filename],
            })
        }
    })
    return newArr
}


classifyLogList(data);
//結果
[
    {
        device_id: "AAAAAAA",
        file_list: ["Log_2019-04-09-00-00.tar","Log_2019-04-09-00-01.tar"],
    },
    {
        device_id: "BBBBBBB",
        file_list: ["Log_2019-04-09-00-02.tar"],
    },
]
相關文章
相關標籤/搜索