简体   繁体   中英

How to convert an object with property and key to Array in JavaScript?

So I have an object that looks like this:

在此处输入图片说明

I want to convert it into an array and after some researching, I did something like this:

Object.keys(langs).map(function (key) { return langs[key]; });

and the output looks like this:

在此处输入图片说明

Although it works, that is not what I wanted. What I wanted to do is something like

[
    {
        "code": "af",
        "lang": "Afrikaans"
    },
    {
        "code": "am",
        "lang": "Amharic"
    },
    {
        "code": "ar",
        "lang": "Arabic"
    }
]

and so forth..

What would be the best way to do this? Any help would be much appreciated..

Object.keys(langs).map(function (key) { return { 'code': key, 'lang': langs[key]}; });

我们返回一个带有属性代码和lang的新对象,而不仅仅是返回值

You can just add code property to your map like so:

 var obj = { "af" : "Afrikaans", "am" : "Amharic", "ar" : "Arabic" } var res = Object.keys(obj).map(e => ({ code: e, lang: obj[e] })) console.log(res); 

如果您有可用的Object#entries ,则可以简洁地写为

langs.entries().map(([code, lang]) => ({code, lang}))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM