JS在深层数据结构中取值方案
let school = {
name: 'Hope middle school',
created: '2001',
classes: [
{
name: '三年二班',
teachers: [
{ name: '张二蛋', age: 26, sex: '男', actor: '班主任' },
{ name: '王小妞', age: 23, sex: '女', actor: '英语老师' }
]
},
{
name: '明星班',
teachers: [
{ name: '欧阳娜娜', age: 29, sex: '女', actor: '班主任' },
{ name: '李易峰', age: 28, sex: '男', actor: '体育老师' },
{ name: '杨幂', age: 111, sex: '女', actor: '艺术老师' }
]
}
]
};
一、原始的方式
school.classes &&
school.classes[0] &&
school.classes[0].teachers &&
school.classes[0].teachers[0] &&
school.classes[0].teachers[0].name
【JS在深层数据结构中取值方案】二、Reduce的方式
const get = ( o, p, d) => p.reduce((xs, x) => (xs && xs[x] ? xs[x] : d), o);
// call
var res = get(school, ['classes', 0, 'teachers', 0, 'name'], '默认值');
console.log(res);
//张二蛋
三、lodash中get方法
_.get(school, 'classes[0].teachers[0].name', '默认值');
参考文献