In the previous article, we only considered single attributes, such as: ({ {name }} ), while a large number of levels of use in Vue, such as: ({ {child.name. firstName}})
Code directly
- How to access name.firstName?
let data = {
name:{
firstName:'刘',,
lastName:'亦菲'
}
}
- We use xxx.yyy.zzz to access the data in the object, which is the dot operator
- You can also say a string path to access object members
function getValueByData(obj,path) {
// 分隔为数据[xxx,yyy,zzz]
let paths = path.split('.');
let res = null;
// 先获取obj.xxx,在取得结果中的yyy,在取得结果中的zzz
res = obj[paths[0]]
res = res[paths[1]]
res = res[parhs[2]]
}
If we find the pattern, we can deal with it in a loop
let res = obj;
let prop;
while(prop = paths.shift()) {
// 取出数组里第一个元素,且改变原数组
res = res[prop] // 赋值
}
return res; // 把结果返回
Let's test it
let res = getValueByData(data,'name.firstName')
console.log(res)
Complete code
<body>
<script type="text/javascript">
let data = {
name:{
firstName:'刘',
lastName:'亦菲'
}
}
function getValueByData(obj,path) {
// 分隔为数据[xxx,yyy,zzz]
let paths = path.split('.');
// let res = null;
// 先获取obj.xxx,在取得结果中的yyy,在取得结果中的zzz
// res = obj[paths[0]]
// res = res[paths[1]]
// res = res[parhs[2]]
let res = obj;
let prop;
while(prop = paths.shift()) {
res = res[prop]
}
return res;
}
let res = getValueByData(data,'name.firstName')
console.log(res)
</script>
</body>