[英]Accessing nested array in a json
讓年齡 = 數據 .filter(isDog) .map(dogYears) .reduce(sum);
毫升/小時
我想找到在 javascript 對象中訪問數組元素的最佳方式。 例如:我想找到每門課程的第一個教員名稱和第一個專業。
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'}
]
}
]
}
],
}
]
};
我知道我可以通過以下方式獲得教員名稱和專業
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;
})
}
使用 Object.assign({}, deptartment.Course) 而不是 Department.Course
嘗試使用以下代碼,但沒有太大區別。
var courses=Object.values(Object.assign({}, deptartment.Course));
var fname = Object.values(Object.assign({}, course.faculty[0].Specialization[0]));
期待
'John': 'science'
'Denis': 'Ecnonomics'
你可以試試這個。 對象中有很多錯誤,包括拼寫錯誤和格式錯誤
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: 124, name: 'Denis', Specialization: [{ name: 'Ecnonomics' }, { name: 'Physics' } ] } ] }], }] } var obj = {}; students.deptartment.forEach((e) => { e.Course.forEach((k) => { k.faculty.forEach((l) => { obj[l.name] = l.Specialization[0].name }) }) }) console.log(obj)
我覺得你的意思department
,而不是deptartment
。 我修改了你的 JSON,因為它有點問題:
var students = {
departments:[
{
name:'Computer Science',
age:20,
Courses:[
{ id: 100000,
name:'Object Oriented Programming',
faculty:[
{
id:123,
name:'John',
Specialization: [
{name: 'science'},
{name: 'Physics'}
]
},
{
id:124,
name:'Denis',
Specialization: [
{name: 'Ecnonomics'},
{name: 'Physics'}
]
}
]
}
],
}]
}
您可以使用map
來實現這種嵌套:
students.departments.map(
department => department.Courses.map(
course => course.faculty.map(
student => ({
name: student.name,
specialization: student.Specialization[0].name // check nulls here!
})
)
)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.