如何动态构建嵌套对象

时间:2019-10-18 10:10:06

标签: javascript arrays object

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

我已经尝试了以下代码来构建对象,但是感觉很hacky,并且无法处理边缘情况。

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)

数据变量将具有不同的长度,但始终是相同的设置。有时它同时包含studentteacher角色,有时只是其中之一。

此数据。

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
  }
}

2 个答案:

答案 0 :(得分:0)

只要您看到类似分组等的数据,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);

答案 1 :(得分:0)

找到以下解决问题的方法:

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)

注意:这仅在给定年份中只有一名学生/老师的情况下有效,否则该值将被覆盖。