我想转换像这样的对象:
{"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中将对象转换为键值对数组?
答案 0 :(得分:255)
您可以使用Object.keys()
和map()
来执行此操作
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) {
return [Number(key), obj[key]];
});
console.log(result);

答案 1 :(得分:72)
最好的方法是:
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}
Object.entries(obj);
如此处所示,调用entries
将返回[key, value]
对,如提问者所要求的那样。
或者,您可以调用Object.values(obj)
,它只返回值。
答案 2 :(得分:44)
Object.entries()
返回一个数组,其元素是与[key, value]
上直接找到的可枚举属性object
对应的数组。属性的顺序与手动循环对象的属性值所给出的顺序相同。
Object.entries
函数几乎返回您要求的确切输出,除了键是字符串而不是数字。
const 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};
console.log(Object.entries(obj));
如果您需要键作为数字,您可以将结果映射到具有回调函数的新数组,该回调函数用从中强制转换的数字替换每对中的键。
const 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};
const toNumericPairs = input => {
const entries = Object.entries(input);
return entries.map(entry => Object.assign(entry, { 0: +entry[0] }));
}
console.log(toNumericPairs(obj));
我在上面的示例中使用箭头函数和Object.assign
作为地图回调,这样我就可以通过利用Object.assign
返回被分配对象的事实将其保留在一条指令中,并且单指令箭头函数的返回值是指令的结果。
这相当于:
entry => {
entry[0] = +entry[0];
return entry;
}
正如@TravisClarke在评论中所提到的,地图功能可以缩短为:
entry => [ +entry[0], entry[1] ]
但是,这将为每个键值对创建一个新数组,而不是修改现有数组,从而使创建的键值对数组的数量翻倍。虽然原始条目数组仍可访问,但它及其条目不会被垃圾回收。
现在,即使使用我们的就地方法仍然使用两个保存键值对的数组(输入和输出数组),数组的总数只会改变一个。输入和输出数组实际上并没有用数组填充,而是对数组的引用,这些引用在内存中占用的空间可以忽略不计。
您可以更进一步,通过就地修改条目数组而不是将其映射到新数组来完全消除增长:
const 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};
const toNumericPairs = input => {
const entries = Object.entries(obj);
entries.forEach(entry => entry[0] = +entry[0]);
return entries;
}
console.log(toNumericPairs(obj));
答案 3 :(得分:14)
如果$Keystone token-get
无法为您效劳,您可以使用另一种变体。
Object.values
答案 4 :(得分:8)
使用 Object.keys
和 Array#map
方法。
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
};
// get all object property names
var res = Object.keys(obj)
// iterate over them and generate the array
.map(function(k) {
// generate the array element
return [+k, obj[k]];
});
console.log(res);

答案 5 :(得分:7)
现在在2018年以ES6为标准的情况下回顾一些答案。
从对象开始:
let const={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};
const obj={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};
console.log(Object.values(obj));
//[9,8,7,6,5,4,3,2,1,0,5]
const obj={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};
console.log(Object.entries(obj));
//[["1",9],["2",8],["3",7],["4",6],["5",5],["6",4],["7",3],["8",2],["9",1],["10",0],["12",5]]
const obj={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};
console.log(Object.entries(obj).map(([k,v])=>[+k,v]));
//[[1,9],[2,8],[3,7],[4,6],[5,5],[6,4],[7,3],[8,2],[9,1],[10,0],[12,5]]
const obj={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};
console.log(Object.entries(obj).reduce((ini,[k,v])=>(ini[k]=v,ini),[]));
//[undefined,9,8,7,6,5,4,3,2,1,0,undefined,5]
这是最后一种方法,它还可以根据键的值重新组织数组顺序。有时这可能是所需的行为(有时不是)。但是现在的好处是,这些值被索引在正确的数组插槽上,这对于在数组插槽上进行搜索是必不可少的。
最后(不是完整问题的一部分,而是为了完整性),如果您需要使用键或值轻松进行搜索,但又不想稀疏数组,没有重复项且无需重新排序而无需转换为数字键(甚至可以访问非常复杂的键),那么数组(或对象)就不是您所需要的。我建议改用Map
:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
let r=new Map(Object.entries(obj));
r.get("4"); //6
r.has(8); //true
答案 6 :(得分:6)
使用Object.entries
以key & value
格式获取Object的每个元素,然后像这样通过map
遍历它们:
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).map(([k, v]) => ([Number(k), v]));
console.log(res);
但是,如果您确定键会以渐进顺序使用,则可以使用Object.values
和Array#map
来执行以下操作:
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};
// idx is the index, you can use any logic to increment it (starts from 0)
let result = Object.values(obj).map((e, idx) => ([++idx, e]));
console.log(result);
答案 7 :(得分:4)
如果您使用的是lodash,可能就像这样简单:
var arr = _.values(obj);
答案 8 :(得分:4)
您可以使用Object.values([])
,如果您尚未使用,则可能需要此polyfill:
const objectToValuesPolyfill = (object) => {
return Object.keys(object).map(key => object[key]);
};
Object.values = Object.values || objectToValuesPolyfill;
https://stackoverflow.com/a/54822153/846348
然后您可以执行以下操作:
var object = {1: 'hello', 2: 'world'};
var array = Object.values(object);
请记住,js中的数组只能使用数字键,因此,如果您在对象中使用了其他键,则它们将变为'0,1,2 ... x``
例如,如果您具有唯一密钥,则删除重复项可能很有用。
var obj = {};
object[uniqueKey] = '...';
答案 9 :(得分:2)
答案 10 :(得分:1)
使用lodash,除了上面提供的答案,你还可以在输出数组中输入密钥。
有:
const array = _.values(obj);
如果obj如下:
{ “art”: { id: 1, title: “aaaa” }, “fiction”: { id: 22, title: “7777”} }
然后数组将是:
[ { id: 1, title: “aaaa” }, { id: 22, title: “7777” } ]
如果你改写('genre'是你选择的字符串):
const array= _.map(obj, (val, id) => {
return { ...val, genre: key };
});
你会得到:
[
{ id: 1, title: “aaaa” , genre: “art”},
{ id: 22, title: “7777”, genre: “fiction” }
]
答案 11 :(得分:1)
我建议这个最简单的解决方案使用Object.entries()
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)
console.log(result);
答案 12 :(得分:1)
这是我简单的准系统实现:
let 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
};
const objectToArray = obj => {
let sol = [];
for (key in obj) {
sol.push([key, obj[key]]);
}
return sol;
};
objectToArray(obj)
答案 13 :(得分:1)
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]]
});
答案 14 :(得分:0)
我们可以将Key的Number更改为String类型,如下所示:
<td><?php echo $sections['ht_id'] ?></td>
<td><?php echo $sections['Sections'] ?></td>
<td><?php echo $sections['ht_descr'] ?></td>
答案 15 :(得分:0)
使用Set实现ES6(ES2015)
您可以使用Array.from()或Spread语法
Array.from()示例
const names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
const uniqueNames = Array.from(new Set(names));
console.log(uniqueNames);
传播语法示例
const names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
const uniqueNames = [...new Set(names)];
console.log(uniqueNames);
答案 16 :(得分:0)
这是我的解决方案,我遇到了同样的问题,似乎该解决方案对我来说很有用。
yourObj = [].concat(yourObj);
答案 17 :(得分:0)
使用传播语法进行转换
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 = [...obj]
console.log(result)
答案 18 :(得分:-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;
}
答案 19 :(得分:-1)
在
中使用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));
答案 20 :(得分:-2)
您可以使用_.castArray(obj)。
示例:
_.castArray({ 'a': 1 });
// => [{ 'a': 1 }]