如何映射/合并结构不同的对象 [英] How to map / merge differently structured objects
本文介绍了如何映射/合并结构不同的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
摘要:
我需要将Students
中的值插入到Employees
对应的值中,以使Students
值出现在与Employees['avg_rate' and 'expense']
相同的数组中;
I need to insert the values from Students
into the Employees
corresponding values so that Students
value appears in the same array as Employees['avg_rate' and 'expense']
;
新的或修改的对象数组应与日期和部门(例如00_Infants)匹配,然后排除学生和员工中都没有的部门.
The new or modified object array should be matched on Dates and Department (ex. 00_Infants) THEN excluding departments that are not present in both Students and Employees.
谢谢.
// "Students" aka "attendance values by department"
Object
0:
00_Infants: 30
01_Ones: 35
02_Twos: 39
03_Threes: 38
04_Fours: 21
05_School_Age: 0
key: "10-10-2019"
__proto__: Object
1: {key: "10-11-2019", 00_Infants: 33, 01_Ones: 35, 02_Twos: 36, …}
2: {key: "10-14-2019", 00_Infants: 30, 01_Ones: 33, 02_Twos: 40, …}
// "employees"
Array(12)
0:
key: "10-10-2019"
values: Array(11)
0:
key: "00_Infants"
value:
avg_rate: 13.236842105263158
expense: 764.1350000000001
__proto__: Object
__proto__: Object
1: {key: "01_Ones", value: {…}}
2: {key: "02_Twos", value: {…}}
3: {key: "03_Threes", value: {…}}
4: {key: "04_Fours", value: {…}}
5: {key: "06_Floater", value: {…}}
6: {key: "07_Office", value: {…}}
7: {key: "08_Administration", value: {…}}
8: {key: "09_Director", value: {…}}
9: {key: "12_Kitchen", value: {…}}
10: {key: "13_Unknown", value: {…}}
length: 11
__proto__: Array(0)
__proto__: Object
1: {key: "10-11-2019", values: Array(10)}
2: {key: "10-14-2019", values: Array(9)}
所需结果:
DESIRED RESULT:
{
Date:"10-09-2019"{
00_Infants: {
avg_rate: 13.39,
expense: 776.58,
attendance: 28
},
01_Ones: {
avg_rate: 13.31,
expense: 716.58,
attendance: 33
},
},
{ // for each date
Date:"10-10-2019"{
// for each department ^
}
}
推荐答案
- Object.values()可用于获取
students
对象和 forEach()可用于迭代这些值. - find()方法可用于在
employees
数组中找到具有匹配日期的员工. - 然后针对学生对象项目中的每个值,使用
find()
查找员工对象中的部门,并添加具有适当值的attendance
属性. - Object.values() can be used to get values of
students
object and forEach() can be used to iterate on these values. - find() method can be used to find the employee in
employees
array with matching date. - Then for each value in student's object item,
find()
can be used to find the department in employee object andattendance
property with appropriate value can be added.
代码:
Object.values(students).forEach(([key, value]) => {
let employee = employees.find(obj => obj.key === value.key);
if (employee) {
Object.entries(value).forEach(([k, v]) => {
if (k !== "key") {
let dept = employee.values.find(dept => dept.key === k);
if (dept) {
dept.value.attendance = v;
}
}
});
}
});
这篇关于如何映射/合并结构不同的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文