如何在 JavaScript 中将对象 {} 转换为键值对的数组 []
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38824349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert an Object {} to an Array [] of key-value pairs in JavaScript
提问by Soptareanu Alex
I want to convert an object like this:
我想转换这样的对象:
{"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}
into an array of key-value pairs like this:
成这样的键值对数组:
[[1,5],[2,7],[3,0],[4,0]...].
How can I convert an Object to an Array of key-value pairs in JavaScript?
如何在 JavaScript 中将对象转换为键值对数组?
回答by Nenad Vracar
You can use Object.keys()
and map()
to do this
你可以使用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);
回答by Pila
The best way is to do:
最好的方法是这样做:
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);
Calling entries
, as shown here, will return [key, value]
pairs, as the asker requested.
调用entries
,如这里所示,将[key, value]
按照提问者的要求返回对。
Alternatively, you could call Object.values(obj)
, which would return only values.
或者,您可以调用Object.values(obj)
,它只会返回值。
回答by Pila
Object.entries()
returns an array whose elements are arrays corresponding to the enumerable property[key, value]
pairs found directly uponobject
. The ordering of the properties is the same as that given by looping over the property values of the object manually.
Object.entries()
返回一个数组,其元素是对应于[key, value]
直接在 上找到的可枚举属性对的数组object
。属性的顺序与通过手动循环对象的属性值给出的顺序相同。
The Object.entries
function returns almost the exact output you're asking for, except the keys are strings instead of numbers.
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));
If you need the keys to be numbers, you could map the result to a new array with a callback function that replaces the key in each pair with a number coerced from it.
如果您需要键为数字,您可以将结果映射到一个带有回调函数的新数组,该函数将每对键中的键替换为从它强制转换的数字。
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));
I use an arrow function and Object.assign
for the map callback in the example above so that I can keep it in one instruction by leveraging the fact that Object.assign
returns the object being assigned to, and a single instruction arrow function's return value is the result of the instruction.
我Object.assign
在上面的例子中使用了一个箭头函数和map 回调,以便我可以通过利用Object.assign
返回被分配给的对象的事实将它保存在一个指令中,并且单个指令箭头函数的返回值是指令的结果。
This is equivalent to:
这相当于:
entry => {
entry[0] = +entry[0];
return entry;
}
As mentioned by @TravisClarke in the comments, the map function could be shortened to:
正如@TravisClarke 在评论中提到的,地图功能可以缩短为:
entry => [ +entry[0], entry[1] ]
However, that would create a new array for each key-value pair, instead of modifying the existing array in place, hence doubling the amount of key-value pair arrays created. While the original entries array is still accessible, it and its entries will not be garbage collected.
但是,这将为每个键值对创建一个新数组,而不是修改现有数组,从而使创建的键值对数组数量加倍。虽然原始条目数组仍可访问,但它及其条目不会被垃圾收集。
Now, even though using our in-place method still uses two arrays that hold the key-value pairs (the input and the output arrays), the total number of arrays only changes by one. The input and output arrays aren't actually filled with arrays, but rather references to arrays and those references take up a negligible amount of space in memory.
现在,即使使用我们的就地方法仍然使用两个包含键值对的数组(输入和输出数组),但数组的总数只改变了一个。输入和输出数组实际上并不是用数组填充的,而是对数组的引用,而这些引用在内存中占用的空间可以忽略不计。
- Modifying each key-value pair in-place results in a negligible amount of memory growth, but requires typing a few more characters.
- Creating a new array for each key-value pair results in doubling the amount of memory required, but requires typing a few less characters.
- 就地修改每个键值对导致的内存增长可以忽略不计,但需要输入更多字符。
- 为每个键值对创建一个新数组会导致所需内存量增加一倍,但需要输入的字符更少。
You could go one step further and eliminate growth altogether by modifying the entries array in-place instead of mapping it to a new array:
您可以更进一步,通过就地修改条目数组而不是将其映射到新数组来完全消除增长:
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));
回答by CarlosH.
To recap some of these answers now on 2018, where ES6 is the standard.
现在在 2018 年回顾其中一些答案,其中 ES6 是标准。
Starting with the object:
从对象开始:
let const={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};
- Just blindly getting the values on an array, do not care of the keys:
- 只是盲目地获取数组上的值,不关心键:
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]
- Simple getting the pairs on an array:
- 简单地获取数组上的对:
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]]
- Same as previous, but with numeric keys on each pair:
- 与之前相同,但每对都有数字键:
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]]
- Using the object property as key for a new array (could create sparse arrays):
- 使用 object 属性作为新数组的键(可以创建稀疏数组):
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]
This last method, it could also reorganize the array order depending the value of keys. Sometimes this could be the desired behaviour (sometimes don't). But the advantage now is that the values are indexed on the correct array slot, essential and trivial to do searches on it.
最后一种方法,它还可以根据键的值重新组织数组顺序。有时这可能是所需的行为(有时不是)。但现在的优点是值被索引在正确的数组槽上,对它进行搜索是必不可少的和微不足道的。
- Map instead of Array
- 映射而不是数组
Finally (not part of the original question, but for completeness), if you need to easy search using the key or the value, but you don't want sparse arrays, no duplicates and no reordering without the need to convert to numeric keys (even can access very complex keys), then array (or object) is not what you need. I will recommend Map
instead:
最后(不是原始问题的一部分,而是为了完整性),如果您需要使用键或值轻松搜索,但您不想要稀疏数组、没有重复和无需重新排序,而无需转换为数字键(甚至可以访问非常复杂的键),那么数组(或对象)就不是您所需要的。我会推荐Map
:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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
回答by bigh_29
Yet another solution if Object.entries
won't work for you.
如果Object.entries
对您不起作用,则还有另一种解决方案。
const obj = {
'1': 29,
'2': 42
};
const arr = Array.from(Object.keys(obj), k=>[`${k}`, obj[k]]);
console.log(arr);
回答by Nageshwar Reddy
回答by Pranav C Balan
Use Object.keys
and Array#map
methods.
用途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);
回答by BlackBeard
Use Object.entries
to get each element of Object in key & value
format, then map
through them like this:
用于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);
But, if you are certain that the keys will be in progressive orderyou can use Object.values
and Array#map
to do something like this:
但是,如果您确定这些键将按渐进顺序排列,您可以使用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);
回答by Adam Boostani
If you are using lodash, it could be as simple as this:
如果您使用的是 lodash,它可以像这样简单:
var arr = _.values(obj);
回答by Yossi
With lodash, in addition to the answer provided above, you can also have the key in the output array.
使用 lodash,除了上面提供的答案之外,您还可以在输出数组中拥有键。
Without the object keys in the output array
没有输出数组中的对象键
for:
为了:
const array = _.values(obj);
If obj is the following:
如果 obj 如下:
{ “art”: { id: 1, title: “aaaa” }, “fiction”: { id: 22, title: “7777”} }
Then array will be:
然后数组将是:
[ { id: 1, title: “aaaa” }, { id: 22, title: “7777” } ]
With the object keys in the output array
使用输出数组中的对象键
If you write instead ('genre' is a string that you choose):
如果您改为编写('genre' 是您选择的字符串):
const array= _.map(obj, (val, id) => {
return { ...val, genre: key };
});
You will get:
你会得到:
[
{ id: 1, title: “aaaa” , genre: “art”},
{ id: 22, title: “7777”, genre: “fiction” }
]