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

时间:2017-01-25 19:51:37

标签: javascript arrays object

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

所以我先创建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]

我该怎么做?

3 个答案:

答案 0 :(得分:1)

var nameList = [];
var countList = [];

var myObj = 
{
    "id": "622",
    "name": "main",
    "sub": {
        "637": {
            "id": "637",
            "name": "name 1",
            "stats": {
                "count": 5
            }
        },
        "638": {
            "id": "638",
            "name": "name 2",
            "stats": {
                "count": 10 
            }
        }
    }
};



for(var key in myObj.sub){
    nameList.push(myObj.sub[key].name);
    countList.push(myObj.sub[key].stats.count);
}

console.log(nameList);
console.log(countList);

答案 1 :(得分:0)

for(var key in obj.sub){
    nameList.push(obj.sub[key].name);
    countList.push(obj.sub[key].stats.count;
}

答案 2 :(得分:0)

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

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

工作示例:https://jsfiddle.net/ry0zqweL/

显然,您可以通过多种方式对其进行优化。它只是说明了众多解决方案中的一个。