我想像这样转换一个对象:

{"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}

输入一个键值对数组,如下所示:

[[1,5],[2,7],[3,0],[4,0]...].

如何将对象转换为JavaScript中的键值对数组?


当前回答

另一个解决方案是Object。输入不适合你。

const obj = { '1': 29, '2': 42 }; const arr = Array.from(Object.keys(obj), k=>['${k}', obj[k]]); 控制台.log(到达);

其他回答

使用for in

var obj = { "10":5, "2":7, "3":0, "4":0, "5":0, "6":0, "7":0,
            "8":0, "9":0, "10":0, "11":0, "12":0 };

var objectToArray = function(obj) {
    var _arr = [];

    for (var key in obj) {
        _arr.push([key, obj[key]]);
    }
    return _arr;
}

console.log(objectToArray(obj));

这是我的解决方案,我有同样的问题,似乎这个解决方案为我工作。

yourObj = [].concat(yourObj);

在Ecmascript 6中,

var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};

var res = Object.entries(obj);

console.log(res);

var obj = “1”:5 “2”:7, “3”:0, “4”:0, “5”:0, “6”:0, “7”:0, “8”:0, “9”:0, “10”:0, “11”:0, “12”:0 ); var res = Object.entries(obj); 游戏机。log (res);

你可以使用_.castArray(obj)。

例子: _。castArray({'a': 1}); // => [{'a': 1}]

递归转换对象到数组

function is_object(mixed_var) {
    if (mixed_var instanceof Array) {
        return false;
    } else {
        return (mixed_var !== null) && (typeof( mixed_var ) == 'object');
    }
}


function objectToArray(obj) {
    var array = [], tempObject;
    for (var key in obj) {

        tempObject = obj[key];

        if (is_object(obj[key])) {
            tempObject = objectToArray(obj[key]);
        }
        array[key] = tempObject;
    }
    return array;
}