将JavaScript对象转换为值数组

时间:2016-04-14 13:44:51

标签: javascript php json

我想用JavaScript对象创建一个数组,其中包含所有对象属性的值。

例如,给定此对象:

{
"firstName": "John",
"lastName": "Smith",
"isAlive": "true",
"age": "25"
}

我想制作这个数组:

var myarray = ['John', 'Smith', 'true', '25'];

我该怎么做?

4 个答案:

答案 0 :(得分:0)

您可以使用for … in循环,如下所示:

var obj = JSON.parse(input);
var array = [];
for (key in obj){
    array.push(obj[key]);
}

答案 1 :(得分:0)

您可以使用Array#map()和数组作为键(对于结果数组中项目的正确顺序,这是必要的。)



var array = [{ "userid": "18061997", "fname": "Mike", "bname": "Brouwer", "admin": "2", "email": "", "username": "promike360", "password": "yz", "phone": "06-36505011", "street": "", "streetnumber": "", "zipcode": "", "city": "" }, { "userid": "123456789", "fname": "Anneke", "bname": "van Spaandonk", "admin": "1", "email": "a.vanspaandonk@tele26.nl", "username": "anneke", "password": "xy", "phone": "06-24157017", "street": "Bunschotenstraat", "streetnumber": "14", "zipcode": "5043 BA", "city": "Tilburg" }],
    keys = ["fname", "bname", "email", "username"],
    result = array.map(function (a) {
        return keys.map(function (k) {
            return a[k];
        });
    });

console.log(JSON.stringify(result, 0, 4));




答案 2 :(得分:0)

你可以这个



var data = {
  "firstName": "John",
  "lastName": "Smith",
  "isAlive": "true",
  "age": "25"
};
var keys = Object.keys(data);
var arr = keys.map(function(index) {
  return data[index];
});
console.log(arr)




答案 3 :(得分:-2)

var array = JSON.parse(json_array)

它将输出一个对象:

var array = {firstName : 'John',lastName :  'Smith',isAlive :  'true', age : '25'};

如果你想要一个带有它的数组,只需通过foreach循环传递它:

var keys = Object.keys(array);
var output = [];
for (var i = 0 ; i < keys.length; i++)
{
    output.push(array[keys[i]]);
}

那就是它。