首页 > 代码库 > object类型转换为Array类型

object类型转换为Array类型

var obj = {a: 1, b: 2, c: 3}; // .... 
var arr = []; 
for(var key in obj){ 
    if(!obj.hasOwnProperty(key)){
        continue;
    }
    var item = {}; 
    item[key] = obj[key]; 
    arr.push(item); 
} 
console.log(arr); // [{a: 1}, {b: 2}, {c: 3}]
// 将Object的属性输出成Array
function objOfPropertyToArr(object) {
    var arr = [];
    var i = 0;
    for (var item in object) {
        arr[i] = item;
        i++;
    }
    return arr;
}

// 将Object的属性值输出成Array
function objOfValueToArr(object) {
    var arr = [];
    var i = 0;
    for (var item in object) {
        arr[i] = object[item];
        i++;
    }
    return arr;
}


/* 
* 测试
*/
var obj = {
    name: "oschina",
    age: "18"
}
objOfPropertyToArr(obj); // 输出["name", "age"]
objOfValueToArr(obj); // 输出["oschina", "18"]

 

object类型转换为Array类型