2017-06-15 88 views
0

讓說我有任何nasted數組對象,我想獲得的所有結構論的是OBJ dinamicly獲取所有對象屬性的任何nasted對象數組的名稱動態地

// any array 
// i use this array 
    var person = [{firstName:"John", lastName:"Doe", age:46}, 
        {firstName:"John", lastName:"Doe", k:46}, 
        {firstName:"John", o:"Doe", age:46}, 
        {firstName:"John", lastName:"Doe", ppp:[]}]; 

//how about if it have one nested 
    var person2 = [{firstName:"John", lastName:"Doe", age:46}, 
        {firstName:"John", lastName:"Doe", k:46}, 
        {firstName:"John", o:"Doe", age:46}, 
        {firstName:"John", lastName:"Doe", ppp:[{fa:"aa",ta:"asfa"}, 
        {fa:"as"}]}]; 
    //i want to achive like this 
    //["firstName", "lastName", "age", "k", "o", ppp: [fa,ta]] 

//how about if it have many nested 
    var person3 = [{firstName:"John", lastName:"Doe", age:46}, 
        {firstName:"John", lastName:"Doe", k:46 gg:[{ddd: 
        [{asar:""magrib}]}]}, 
        {firstName:"John", o:"Doe", age:46 kk:["aaa"]}, 
        {firstName:"John", lastName:"Doe", ppp:[{fa:"aa",ta:"asfa"}, 
        {fa:"as"}]}]; 

,我運行函數來獲得屬性附加傷害,但我能做到這一點在層中的一個,如果對象的這種滿足陣列我想這個函數來生成屬性名稱

function get_key (Obj,p){ 
    Obj.forEach(function(d,i){ 
    for (property in d) { 
    var type = typeof(d[property]) 
    if(p.indexOf(property)<0){ 

     if (type!=="object"){ 
     p.push(property) 
     //console.log('ok') 
     }else{ 

     //if meet object how can i make this do the same thing? 
     // so it can dynamicly getattribute name 
     p[property]= p[property]='jj' 
     } 
    } 
    } 
    }) 
    return p 
} 

var p = get_key (person,[]) 
document.getElementById("demo").innerHTML = p; 
console.log(p) 

//and if we console it it return 
//["firstName", "lastName", "age", "k", "o", ppp: "jj"] 
+0

如果您花時間修復問題的拼寫,語法和標點符號,您可能會得到一些答案。事實上,它很難閱讀。使用* Obj *作爲引用數組的變量的名稱是令人困惑的。 – RobG

+0

對不起,但我只是不能找到編輯按鈕 – KEKUATAN

回答

0

完成它可以

function get_key (Obj,p,id){ 
var p2 
    Obj.forEach(function(d,i){ 
    if(typeof(d)!=='object'){ 
     return 
    } 
    for (property in d) { 
    var type = typeof(d[property]) 

    if(p.indexOf(property)<0){ 

     if (type!=="object"){ 
     p.push(property) 
     //console.log('ok') 
     //p[property]='jj' 
     }else{ 
     console.log(property,[]) 
     var pe= property 
     p2 = get_key (d[property],[],property) 
     p[pe]=p2 
     } 
    } 
    } 
    }) 
    return p 
} 

var p = get_key (person,[])