Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/468.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript从对象数据创建2个数组_Javascript_Arrays_Object - Fatal编程技术网

Javascript从对象数据创建2个数组

Javascript从对象数据创建2个数组,javascript,arrays,object,Javascript,Arrays,Object,我有一些数据,我需要一个创建2个数组的循环 因此,我首先创建两个阵列: namelist = []; countList = []; { "id": "622", "name": "main", "sub": { "637": { "id": "637", "name": "name 1", "stats": { "count": 5

我有一些数据,我需要一个创建2个数组的循环

因此,我首先创建两个阵列:

namelist = [];
countList = [];


{
    "id": "622",
    "name": "main",
    "sub": {
        "637": {
            "id": "637",
            "name": "name 1",
            "stats": {
                "count": 5
            }
        },
        "638": {
            "id": "638",
            "name": "name 2",
            "stats": {
                "count": 10 
            }
        }
    }
}
本例的预期结果为:

姓名列表:

['name 1', 'name 2']
有关countList:

[5, 10]

如何执行此操作?

对象。键可以帮助您浏览对象属性。与对象相关的示例:

for(var key in obj.sub){
    nameList.push(obj.sub[key].name);
    countList.push(obj.sub[key].stats.count;
}
var namelist = [],
  countList = [],
  obj = {
    "id": "622",
    "name": "main",
    "sub": {
      "637": {
        "id": "637",
        "name": "name 1",
        "stats": {
          "count": 5
        }
      },
      "638": {
        "id": "638",
        "name": "name 2",
        "stats": {
          "count": 10
        }
      }
    }
  };

Object.keys(obj.sub).forEach(function(item) {
    namelist.push(obj.sub[item].name);
    countList.push(obj.sub[item].stats.count);
});

console.log(namelist, countList);
工作示例:


显然,您可以在许多方面对其进行优化。这只是众多解决方案中的一个。

您是否有我们可以尝试并帮助您修复的循环?而不是我们中的一个为你解决问题可能重复的
var namelist = [],
  countList = [],
  obj = {
    "id": "622",
    "name": "main",
    "sub": {
      "637": {
        "id": "637",
        "name": "name 1",
        "stats": {
          "count": 5
        }
      },
      "638": {
        "id": "638",
        "name": "name 2",
        "stats": {
          "count": 10
        }
      }
    }
  };

Object.keys(obj.sub).forEach(function(item) {
    namelist.push(obj.sub[item].name);
    countList.push(obj.sub[item].stats.count);
});

console.log(namelist, countList);