0
var json={
  name: 'john',
  age: '80',
  child: [
    {
      name: 'sindy',
      age: '60',
      child: [
        {
          name: 'bob',
          age: '40',
          child: [
            {
              name: 'sany',
              age: '20'
            }
          ]
        }
      ]
    },
    {
      name: 'susan',
      age: '70'
    }
  ]
}  

I want to get all name's value ,and then,put them in an array. like:

['john','sindy','bob','sany','susan']

at first,should I know about deep and shallow copy?

epascarello
  • 204,599
  • 20
  • 195
  • 236
hui
  • 591
  • 7
  • 22

1 Answers1

5

It is a basic recursion problem. It is as simple as checking to see if the person has a child array, than process the children.

var json={
  name: 'john',
  age: '80',
  child: [
    {
      name: 'sindy',
      age: '60',
      child: [
        {
          name: 'bob',
          age: '40',
          child: [
            {
              name: 'sany',
              age: '20'
            }
          ]
        }
      ]
    },
    {
      name: 'susan',
      age: '70'
    }
  ]
};

var names = [];  //where we will store the names
function findName (obj) {    
    names.push(obj.name);  //get the current person's name
    if(obj.child) obj.child.forEach(findName);  //if we have a child, loop over them
}
findName(json);
console.log(names);
epascarello
  • 204,599
  • 20
  • 195
  • 236