簡體   English   中英

如何格式化JSON對象數組(JavaScript)

[英]how to format JSON object array (Javascript)

我在一個艱苦的要求中掙扎,我不知道該如何應對

我收到了一個數組,如下所示:

[{
    "student": "21_A_1",
    "sport": "badminton"
}, {
    "student": "21_C_1",
    "sport": "badminton"
}, {
    "student": "21_A_2",
    "sport": "badminton"
}, {
    "student": "21_B_1",
    "sport": "football"
}, {
    "student": "21_A_2",
    "sport": "football"
}]

要求:將其轉換為以下格式的數組:

[{
    "student": "21_A_1",
    "sport": ["badminton"]
}, {
    "student": "21_C_1",
    "sport": ["badminton"]
}, {
    "student": "21_A_2",
    "sport": ["badminton","football"]
}, {
    "student": "21_B_1",
    "sport": ["football"]
}]

我發現lodash庫具有“ group by”功能,返回的結果非常接近,但不符合預期:

_.groupBy(array, 'student');

結果:

{
    "21_A_1": [{
        "student": "21_A_1",
        "sport": "badminton"
    }],
    "21_C_1": [{
        "student": "21_C_1",
        "sport": "badminton"
    }],
    "21_A_2": [{
        "student": "21_A_2",
        "sport": "badminton"
    }, {
        "student": "21_A_2",
        "sport": "football"
    }],
    "21_B_1": [{
        "student": "21_B_1",
        "sport": "football"
    }]
}

任何建議都非常感謝。

我們可以使用數組的“ .reduce”功能並匯總結果,如下所示

 var test = [{ "student": "21_A_1", "sport": "badminton" }, { "student": "21_C_1", "sport": "badminton" }, { "student": "21_A_2", "sport": "badminton" }, { "student": "21_B_1", "sport": "football" }, { "student": "21_A_2", "sport": "football" }] const result = test.reduce((res,x)=>{ res[x.student] = res[x.student] || { student:x.student,sport:[]} res[x.student].sport.push(x.sport) return res; },{}) console.log(result) 

您需要將分組項目與其sport屬性進行映射,並使用分組信息構建新對象。

 var array = [{ student: "21_A_1", sport: "badminton" }, { student: "21_C_1", sport: "badminton" }, { student: "21_A_2", sport: "badminton" }, { student: "21_B_1", sport: "football" }, { student: "21_A_2", sport: "football" }], grouped = _(array) .groupBy('student') .map((group, student) => ({ student, sport: _.map(group, 'sport') })) .value(); console.log(grouped); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script> 

結合使用Array.prototype.reduce()Object.values()

 const data = [{"student": "21_A_1","sport": "badminton"}, {"student": "21_C_1","sport": "badminton"}, {"student": "21_A_2","sport": "badminton"}, {"student": "21_B_1","sport": "football"}, {"student": "21_A_2","sport": "football"}]; const result = Object.values( data.reduce((a, c) => ((a[c.student] = a[c.student] || {student: c.student, sport: []}).sport.push(c.sport), a), {}) ); console.log(result); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM