Calculate the sum of ages for dogs in a given dataset and convert them to dog years.
mL/hr
I am looking for the optimal method to access array elements within a JavaScript object. For example, I want to retrieve the first faculty name and specialization for each course.
var students =
{
deptartment:[
{
name:'Computer Science',
age:20,
Course:[
{ id: 100000
name:'Object Oriented Programming',
faculty:[
{
id:123,
name:'John',
Specialization: [
{name: 'science'},
{name: 'Physics'}
]
}
]
},
{ id: 100001
name:'C#',
faculty:[
{
id:124,
name:'Denis',
Specialization: [
{name: 'Ecnonomics'},
{name: 'Physics'}
]
}
]
}
],
}
]
};
To get the faculty name and specialization, you can use the following code:
var courses= deptartment && deptartment.Course ;
var facultyWithSpecialization= {};
if(courses){
courses.forEach(course =>{
var fname = course.faculty && course.faculty[0].name;
var s= course.faculty && course.faculty.Specialization;
facultyWithSpecialization[fname] = s && s[0].name;
})
}
Instead of department.Course, consider using Object.assign({}, department.Course).
An attempt was made with the following code but it did not yield significant results.
var courses=Object.values(Object.assign({}, deptartment.Course));
var fname = Object.values(Object.assign({}, course.faculty[0].Specialization[0]));
Expected output:
'John': 'science'
'Denis': 'Ecnonomics'