简体   繁体   English

将javascript列表转换为字典

[英]Convert a javascript list to dictionary

I'm trying to convert a javascript list to a dictionary with a specified key. 我正在尝试将javascript列表转换为具有指定键的字典。 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. letlist = list实际上是问题中的拼写错误 - 它在我的真实代码中是正确的。 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修复拼写错误,我们假设您想要一个包含三个对象的数组),那么您只是不使用结果:

  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: 我会帮助@TJ Crowder的答案:Ecma Script 6(ES6)无法在旧浏览器和Internet Explorer中呈现(只是箭头函数=> ),您可以使用下面的代码:

 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: ES6中的典型事物是:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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