简体   繁体   中英

Convert a javascript list to dictionary

I'm trying to convert a javascript list to a dictionary with a specified key. I'm using the following code:

 let list = ['cat', 'rabbit', 'fish'] list = list.map(x => { return ({ animal: x }); }) console.log(list); 

Of course this doesn't work. Edit: It actually does

Expected result:

[
  {
    "animal": "cat"
  },
  {
    "animal": "rabbit"
  },
  {
    "animal": "fish"
  }
]

Edit:

let and list=list was in fact a typo in the question - it is correct in my real code. I didnt test this snippet as I didnt think it worked. I also then confused myself and did type the expected result wrong. My code is more complex and it didn't make sense to post it all. As works, I think my bug must be elsewhere. Thanks for the help.

Of course this doesn't work.

It does (if we fix the typo in Let and we assume you wanted an array of three objects), you're just not using the result:

  let list = ['cat', 'rabbit', 'fish'] // vvvvvvv list = list.map(x => { return({animal: x}); }); console.log(list); 

Or more briefly with a concise arrow function:

 let list = ['cat', 'rabbit', 'fish'] list = list.map(x => ({animal: x})); console.log(list); 

I'll make an asside to @TJ Crowder's answer: Ecma Script 6 (ES6) could not render in old browsers and Internet Explorer (just arrow functions => ) you could use code below instead:

 var list = ['cat', 'rabbit', 'fish'] list = list.map(function(x) { return ({ animal: x }); }); console.log(list); 

If you'll keep the original list, you could use code below:

 var list = ['cat', 'rabbit', 'fish'] var result = list.map(function(x) { return ({ animal: x }); }); console.log(list); console.log(result); 

Typical things in ES6 are:

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