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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:00:26  来源:igfitidea点击:

JavaScript: How to turn a dictionary into a list of elements?

javascript

提问by brooksbp

What is the most elegant way to turn this:

什么是最优雅的方式来改变这个:

{
    'a': 'aa',
    'b': 'bb'
}

into this:

进入这个:

[
    ['a', 'aa'],
    ['b', 'bb']
]

回答by McGarnagle

Just iterate through the keys:

只需遍历键:

var dict = { 'a': 'aa', 'b': 'bb' };
var arr = [];

for (var key in dict) {
    if (dict.hasOwnProperty(key)) {
        arr.push( [ key, dict[key] ] );
    }
}

Fiddle(updated per @Hyman's comment, only add direct properties)

Fiddle(根据@Hyman 的评论更新,仅添加直接属性)

回答by Aadit M Shah

Most JavaScript engines now support the Object.entriesfunction:

大多数 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)

使用lodash.js(或underscore.js

var obj = {'a': 'aa', 'b': 'bb'};

_.pairs(obj);

//[['a', 'aa'], ['b', 'bb']]

lodash.jsis 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.getOwnPropertyNamesand Array.prototype.map

如果您的浏览器支持Object.getOwnPropertyNamesArray.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.keyswill work too. In this example both would have the same result.

正如Crazy Train指出的那样,如果您只对可枚举的属性感兴趣,Object.keys也可以使用。在这个例子中,两者都会有相同的结果。