// Need: recursively get all names in the data


let obj = {
    name:'xx'.children:[
        {
            name:'ff'.age:'11'.children: [{name:'sss'.age:2222.children: [{name: {ss:11},
                    age:77}]}]},]}// Two data structures
Object {name, chidren []}
Object [{name, chidren[]},{name, chidren[]}]
Copy the code

// Method 1 applies to both data structures 1 and 2
let getName = (obj) = >{
    let isArr = Array.isArray(obj);
    let reslut = [];
    if(isArr){
        obj.forEach(item= >{ reslut.push(... getName(item)); }); }else{
        reslut.push(obj.name)
        if(obj.children){
            reslut.push(...getName(obj.children));
        }
    }
    return reslut;
}
console.log(getName(obj))
Copy the code

// Method 2: for data structure 1
let getResult = (data,list=[]) = >{
    list.push(data.name);
    let isArr = Array.isArray(data.children);
    if(isArr){
        data.children.forEach(item= >{
            getResult(item,list)
        })
    }
    return list;
}
console.log(111);
console.log(getResult(obj))
Copy the code
// Method 3: use the json.stringify API
let names = [];
// console.log(JSON.stringify(obj))
JSON.stringify(obj,(key,value) = >{
    if(key==='name') names.push(value)
    return value
})
console.log(names)
Copy the code