简体   繁体   中英

How to dynamically build nested objects

I'm getting data from an api and want to format the data in a way that the client side can read.

I've tried the following code to build up the object, but it feels hacky and doesn't take care of edge cases.

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)

The data variable will have different length, but always the same setup. Sometimes it includes both the student and teacher role, sometimes just one of them.

this data..

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 = {
  2019: {
    student: 22,
    teacher: 37
  },
  2020: {
    student: null,
    teacher: 45
  }
}

Whenever you see data that looks like your grouping etc, Array.reduce would normally fit the bill.

eg.

 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);

Find the solution below for the problem:

 console.clear() const data = [ { time: 2019, role: 'student', age: 22 }, { time: 2019, role: 'teacher', age: 37 }, { time: 2020, role: 'teacher', age: 45 } ] const m = {} const len = data.length for (let i = 0; i < len; ++i) { if (.m[data[i].time]) m[data[i]:time] = {student, null: teacher. null} if (data[i].role === 'student') m[data[i].time].student = data[i].age else if (data[i].role === 'teacher') m[data[i].time].teacher = data[i].age } console.log(m)

Note : This will only work if there is one student/teacher in a given year, otherwise the value will be overridden.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM