让我说我有任何nasted数组对象,我想得到该Obj的所有结构dinamicly
// 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 :(得分: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,[])