JavaScript:如何将字典转换为元素列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17625663/
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
JavaScript: How to turn a dictionary into a list of elements?
提问by brooksbp
What is the most elegant way to turn this:
什么是最优雅的方式来改变这个:
{
'a': 'aa',
'b': 'bb'
}
into this:
进入这个:
[
['a', 'aa'],
['b', 'bb']
]
回答by McGarnagle
回答by Aadit M Shah
Most JavaScript engines now support the Object.entries
function:
大多数 JavaScript 引擎现在都支持该Object.entries
功能:
const list = Object.entries({
a: "aa",
b: "bb"
});
console.log(list); // [['a', 'aa'], ['b', 'bb']]
For older engines, you can write a polyfill for it as follows:
对于较旧的引擎,您可以为它编写一个 polyfill,如下所示:
if (typeof Object.entries !== "function")
Object.entries = obj => Object.keys(obj).map(key => [key, obj[key]]);
Hope that helps.
希望有帮助。
回答by holographic-principle
Using lodash.js(or underscore.js)
var obj = {'a': 'aa', 'b': 'bb'};
_.pairs(obj);
//[['a', 'aa'], ['b', 'bb']]
lodash.js
is an aspiring successor to underscore.js
, originated as a fork of the original project. In my opinion, a must use for anyone who values their time.
lodash.js
是一个有抱负的继承者underscore.js
,起源于原始项目的一个分支。在我看来,任何重视时间的人都必须使用它。
回答by Paul S.
If you have a browser that supports Object.getOwnPropertyNames
and Array.prototype.map
如果您的浏览器支持Object.getOwnPropertyNames
和Array.prototype.map
var obj = {'a': 'aa', 'b': 'bb'}, arr;
arr = Object.getOwnPropertyNames(obj).map(function(e) {return [e, obj[e]];});
// [["a", "aa"], ["b", "bb"]]
Browser support table here
浏览器支持表在这里
As Crazy Trainpoints out, if you are only interested in enumerable properties, Object.keys
will work too. In this example both would have the same result.
正如Crazy Train指出的那样,如果您只对可枚举的属性感兴趣,Object.keys
也可以使用。在这个例子中,两者都会有相同的结果。