帮助我从以下JSON数据中获取所有学生的ID和大学ID的数组。 我想拥有;
//to store id of all colleges.
var collegeid = [];
//store id of all students.
var studentsid = [];
//students id as per college:
var studentsIdInCollege1 = [];
var data = {
"college":[
{
"id":1,
"school":"abc",
"course":"cde",
"students":[
{
"id":1,
"name":"abc 123",
"number":"156888"
},
{
"id":2,
"name":"abc 123",
"number":"156888"
}
]
},
{
"id":2,
"school":"xyz",
"course":"lopl",
"students":[
{
"id":3,
"name":"abc 123",
"number":"156888"
},
{
"id":4,
"name":"abc 123",
"number":"156888"
}
]
}
]
}
`
答案 0 :(得分:2)
对于大学,只需map
大学数组到每个对象的id
。对于学生,使用[].concat(...
分散学生ID的地图并获得一个扁平的对象:
const input = {
"college":[
{
"id":1,
"school":"abc",
"course":"cde",
"students":[
{
"id":1,
"name":"abc 123",
"number":"156888"
},
{
"id":2,
"name":"abc 123",
"number":"156888"
}
]
},
{
"id":2,
"school":"xyz",
"course":"lopl",
"students":[
{
"id":3,
"name":"abc 123",
"number":"156888"
},
{
"id":4,
"name":"abc 123",
"number":"156888"
}
]
}
]
}
const collegeIds = input.college.map(({ id }) => id);
console.log('collegeIds: ' + collegeIds);
const studentIds = [].concat(...input.college.map(({ students }) => students.map(({ id }) => id)));
console.log('studentIds: ' + studentIds);
答案 1 :(得分:1)
使用.map()
获取大学ID:
let collegeIds = data.college.map(({ id }) => id);
对学生ID使用.reduce()
:
let studentIds = data.college.reduce((a, c) => (
a.concat(c.students.map(({ id }) => id))
), []);
使用.reduce()
获取一个数组数组,其中每个数组都包含student id:
let studentInEachCollege = data.college.reduce((a, c) => (
a.push(c.students.map(({ id }) => id)), a
), []);
这将允许您使用第一个大学的studentInEachCollege[0]
索引,第二个大学studentInEachCollege[1]
等索引访问每个大学生,依此类推。
<强>演示:强>
var data = {
"college":[
{
"id":1,
"school":"abc",
"course":"cde",
"students":[
{
"id":1,
"name":"abc 123",
"number":"156888"
},
{
"id":2,
"name":"abc 123",
"number":"156888"
}
]
},
{
"id":2,
"school":"xyz",
"course":"lopl",
"students":[
{
"id":3,
"name":"abc 123",
"number":"156888"
},
{
"id":4,
"name":"abc 123",
"number":"156888"
}
]
}
]
};
let collegeIds = data.college.map(({ id }) => id);
let studentIds = data.college.reduce((a, c) => (
a.concat(c.students.map(({ id }) => id))
), []);
let studentInEachCollege = data.college.reduce((a, c) => (
a.push(c.students.map(({ id }) => id)), a
), []);
console.log(collegeIds);
console.log(studentIds);
console.log(studentInEachCollege);
<强>文档:强>
答案 2 :(得分:1)
// College ids
var cID = data.college.map((c) => { return c.id});
// Students
// It returns two arrays so you need to reduce it...
var students = data.college.map((c) => { return c.students});
var allStudents = students.reduce((a,b) => {return a.concat(b)}, []);
// IDs
var sID = allStudents.map((c) => { return c.id});