遍歷多層巢狀物件
阿新 • • 發佈:2019-01-28
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style></style>
</head>
<body>
</body>
<script>
//result物件包含各種資料型別(字串、null、Number、Function、Date...)
var result = {a : 'aa',b :4,c : '' ,d :{ e :{f : null,g : function () {
}}},h : 3>5,i : [1,4,5],j :[{k:'kkk',l : ['abc','edf']}],n : new Date(),p:undefined,r :{ s : {t :{ u : 'uuu'}}}};
//獲取物件所有的key值
function getKeys(obj){
//es6新語法 Object.prototype.toString方法精準判斷引數值 屬於哪種型別
if(Object.prototype.toString.call(obj) === '[object Object]' ){
var arr = [];
(function getKeysFn(o, char) {
for(var key in o){
//判斷 物件的屬性是否需要拼接'.',如果是第一層物件屬性不拼接,否則拼接'.'
var newChar = char == '' ? key : char + '.' + key;
if (Object.prototype.toString.call(o[key]) === '[object Object]' ) {
// 如果屬性對應的屬性值仍為可分解的物件,使用遞迴函式繼續分解,直到最裡層
getKeysFn(o[key],newChar);
}else{
arr.push(newChar);
}
}
})(obj, '')
return arr;
}else{
console.log('傳入的不是一個真正的物件噢');
}
}
function getValue(obj){
try{
console.log(JSON.stringify(obj));
return JSON.stringify(obj);
}catch(ex){
console.log('輸入資料的格式存在錯誤');
}
}
getKeys(result);
getValue(result.p);
getValue(result.r.s.t.u);
</script>
</html>