我们在前端开发中经常需要处理 JavaScript 对象,有时候需要操作嵌套对象的属性,这时候就需要使用一个方便快捷的方法来访问对象的属性,这个时候 get-object-path 就派上用场了。
get-object-path 简介
get-object-path 是一个从嵌套对象中获取属性值的 JavaScript 工具库。它提供了一个方法 getObjectPath,该方法可以获取嵌套对象中的某个属性的值。
为什么使用 get-object-path
如果你需要操作嵌套对象的属性,例如:
// www.javascriptcn.com code example
const user = {
id: '123456',
name: '张三',
age: 18,
address: {
city: {
name: '北京',
code: '010'
},
province: {
name: '北京市',
code: '110000'
}
}
}
const cityName = user.address.city.name // 北京
const provinceCode = user.address.province.code // 110000上述方式可以很快地获取我们需要的属性值,但是当我们需要处理更加复杂的嵌套对象时,代码就会变得非常冗长且难以维护,例如:
// www.javascriptcn.com code example
const person = {
id: '001',
name: '小明',
gender: 'male',
age: 18,
education: {
level: '本科',
school: {
name: '清华大学',
address: {
city: '北京',
district: '海淀区'
},
logo: 'https://www.example.com/logo.jpg'
},
major: '计算机科学与技术'
},
work: {
company: {
name: '字节跳动',
logo: 'https://www.example.com/logo.jpg'
},
department: 'ByteDance AI Lab'
}
}
const companyName = person.work.company.name
const schoolName = person.education.school.name如果使用 get-object-path 来获取这些属性
const getObjectPath = require('get-object-path')
const companyName = getObjectPath(person, 'work.company.name')
const schoolName = getObjectPath(person, 'education.school.name')代码就会变得更加简洁明了且易于维护。
get-object-path 使用方法
安装 get-object-path
npm install get-object-path
使用方法如下:
const getObjectPath = require('get-object-path')
const value = getObjectPath(object, path)其中:
object:操作的对象path:访问属性的路径字符串,可以是点分隔符来表示嵌套属性(例如:user.address.city.name)也可以是数组表示法(例如:['user', 'address', 'city', 'name'])
示例代码
// www.javascriptcn.com code example
const getObjectPath = require('get-object-path')
const person = {
id: '001',
name: '小明',
gender: 'male',
age: 18,
education: {
level: '本科',
school: {
name: '清华大学',
address: {
city: '北京',
district: '海淀区'
},
logo: 'https://www.example.com/logo.jpg'
},
major: '计算机科学与技术'
},
work: {
company: {
name: '字节跳动',
logo: 'https://www.example.com/logo.jpg'
},
department: 'ByteDance AI Lab'
}
}
const companyName = getObjectPath(person, 'work.company.name')
const schoolName = getObjectPath(person, 'education.school.name')
console.log(companyName) // 字节跳动
console.log(schoolName) // 清华大学总结
通过 get-object-path 可以方便快捷地获取嵌套对象的属性值,在处理复杂对象时可以使代码更具可读性,易于维护。
如果你需要在前端开发中使用嵌套对象,那么 get-object-path 工具库是一个不错的选择,尝试使用它,你会体会到它所带来的便捷和舒适。
Source: FunTeaLearn,Please indicate the source for reprints https://funteas.com/post/6005513f81e8991b448ce4fa