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

{"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中的键值对数组?


当前回答

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 }
let objectKeys = Object.keys(obj);

let answer = objectKeys.map(value => {
    return [value + ':' + obj[value]]
});

其他回答

最好的办法是:

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 result = Object.entries(obj); 控制台.log(结果);

如图所示,调用条目将根据调用者的请求返回[key, value]对。

或者,也可以调用Object.values(obj),它只返回值。

递归转换对象到数组

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

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

我们可以将数字改为字符串类型的键如下所示:

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 result = Object.keys(obj).map(function(key) { 返回 [字符串(键), 对象[键]]; }); 控制台.log(结果);

下面是es6使用扩展操作符和Object.entries的“新”方法。

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

const dataSpread = [...Object.entries(data)];

// data spread value is now:
[
  [ '1', 5 ],  [ '2', 7 ],
  [ '3', 0 ],  [ '4', 0 ],
  [ '5', 0 ],  [ '6', 0 ],
  [ '7', 0 ],  [ '8', 0 ],
  [ '9', 0 ],  [ '10', 0 ],
  [ '11', 0 ], [ '12', 0 ]
]