通过JavaScript从json获取所有键值

时间:2016-01-13 03:48:27

标签: javascript json

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'
    }
  ]
}  

我希望获得所有名称的值,然后将它们放入数组中。像:

['john','sindy','bob','sany','susan']
首先,我应该知道深浅的副本吗?

1 个答案:

答案 0 :(得分:5)

这是一个基本的递归问题。它就像检查这个人是否有子数组一样简单,而不是处理孩子。



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);