Can you please help me how can I access "name" key from obj3. Please find below example.
I am looking for good approch, I dont want to do :
obj.obj1.obj2.obj3.name
var obj = {
obj1 : {
obj2: {
obj3: {
name: 'jhon'
}
}
}
}
Thanks!
您可以在理论上使用es6解构
const {obj1: {obj2: { obj3: {name: b}}}} = obj console.log(b) //jhon
You can use a recursive function that returns the first non object element.
Obviously this functions works only for structures where the nested objects contains only one object or one value.
var obj = {
obj1 : {
obj2: {
obj3: {
name: 'jhon'
}
}
}
}
const getName = (obj) => {
if (typeof obj[Object.keys(obj)] === 'object') {
return getName(obj[Object.keys(obj)])
} else {
return obj[Object.keys(obj)]
}
}
getName(obj)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.