如何动态构建嵌套对象

我正在从 api 获取数据,并希望以客户端可以读取的方式格式化数据。


我已经尝试了以下代码来构建对象,但感觉很笨拙并且没有处理边缘情况。


function myHackyFunction(data){

result = {}


data.forEach(el => {

        const timeStamp = el['time']

        result[timeStamp] = { teacher: null, student: null }

    })

data.forEach(el => {

        const role = el['role']

        const timeStamp = el['time']

        const age = el['age']

        if (role.includes('teacher')) {

            result[timeStamp].teacher = age

        }

        if (role.includes('student')) {

            result[timeStamp].student = age

        }

    })

  return result

}

myHackyFunction(data)

数据变量将有不同的长度,但总是相同的设置。有时它包括student和teacher角色,有时只是其中之一。


这个数据..


const data = [

  {

    time: 2019,

    role: 'student',

    age: 22

  },

  {

    time: 2019,

    role: 'teacher',

    age: 37

  },

  {

    time: 2020,

    role: 'teacher',

    age: 45

  }

]

..应该是这样的:


const desiredData = {

  2019: {

    student: 22,

    teacher: 37

  },

  2020: {

    student: null,

    teacher: 45

  }

}


HUH函数
浏览 154回答 2
2回答

鸿蒙传说

每当您看到看起来像您的分组等的数据时,Array.reduce通常都符合要求。例如。const data = [  {    time: 2019,    role: 'student',    age: 22  },  {    time: 2019,    role: 'teacher',    age: 37  },  {    time: 2020,    role: 'teacher',    age: 45  }];//..should look like:const desiredData = data.reduce((a, v) => {  a[v.time] = a[v.time] || {student: null, teacher: null};  a[v.time][v.role] = v.age;  return a;}, {});console.log(desiredData);

狐的传说

找到以下问题的解决方案:console.clear()const data = [&nbsp; {&nbsp; &nbsp; time: 2019,&nbsp; &nbsp; role: 'student',&nbsp; &nbsp; age: 22&nbsp; },&nbsp; {&nbsp; &nbsp; time: 2019,&nbsp; &nbsp; role: 'teacher',&nbsp; &nbsp; age: 37&nbsp; },&nbsp; {&nbsp; &nbsp; time: 2020,&nbsp; &nbsp; role: 'teacher',&nbsp; &nbsp; age: 45&nbsp; }]const m = {}const len = data.lengthfor (let i = 0; i < len; ++i) {&nbsp; &nbsp; if (!m[data[i].time]) m[data[i].time] = {student: null, teacher: null}&nbsp; if (data[i].role === 'student')&nbsp; &nbsp; m[data[i].time].student = data[i].age&nbsp; else if (data[i].role === 'teacher')&nbsp; &nbsp; m[data[i].time].teacher = data[i].age&nbsp;}console.log(m)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript