从JavaScript对象创建数组

时间:2016-11-01 11:04:59

标签: javascript

我有一些看起来像这样的数据:

{
  "obj":
  [
    {
      "name": "name1",
      "age": "24"
    },
    {
      "name": "name2",
      "age": "17"
    }
  ]
}

我需要做的是从中创建2个数组。

例如:

namelist[];
agelist[];

所以结果将是:

namelist: ['name1', 'name2'];

agelist: [24, 17];

我的问题是,我该怎么做?

5 个答案:

答案 0 :(得分:3)

这是你想要的吗?

var zz={
    "obj": [
        {
            "name": "name1",
            "age": "24"
        },
        {
            "name": "name2",
            "age": "17"
        }
    ]
}

namelist=[];
agelist=[];
zz.obj.forEach(function(rec){
  namelist.push(rec.name);
  agelist.push(rec.age);
})

console.log(namelist,agelist)

答案 1 :(得分:2)

var namelist = [];
var agelist = [];
for(var i in obj.obj){
    namelist.push(obj.obj[i].name);
    agelist.push(obj.obj[i].age);
}

console.log(namelist, agelist);

答案 2 :(得分:1)

您可以使用此ES6代码,并使用单一加号将年龄作为数字。假设您的对象存储在变量data中:

var namelist = data.obj.map( o => o.name );
var agelist = data.obj.map( o => +o.age );

var data = {
    "obj": [
        {
            "name": "name1",
            "age": "24"
        },
        {
            "name": "name2",
            "age": "17"
        }
    ]
};

var namelist = data.obj.map( o => o.name );
var agelist = data.obj.map( o => +o.age );

console.log(namelist);
console.log(agelist);

答案 3 :(得分:0)

使用jquery map函数或者你可以使用javascript for循环遍历对象并将其推送到数组中并使用push()函数。请参阅Loop through an array in JavaScript

Jquery的

var data = {
    "obj": [
        {
            "name": "name1",
            "age": "24"
        },
        {
            "name": "name2",
            "age": "17"
        }
    ]
}

var name = $.map(data.obj, function(value, index) {
    return value.name;
});
var age = $.map(data.obj, function(value, index) {
    return value.age;
});

console.log(name);
console.log(age);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

的Javascript

var data = {
        "obj": [
            {
                "name": "name1",
                "age": "24"
            },
            {
                "name": "name2",
                "age": "17"
            }
        ]
    }
    var names = [], ages=[];
    data.obj.forEach(function(value, index) {

        names.push(value.name);
        ages.push(value.age);
    });
console.log(names,ages);

答案 4 :(得分:0)

var arr = $.map(myObj, function(value, index) {
return [value];
});


console.log(arr);

如果你没有使用Jquery,那么:

var arr = Object.keys(myObj).map(function (key) 
 { return obj[key]; 
});`