Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a javascript list to dictionary

Tags:

javascript

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.

like image 308
Codematcha Avatar asked Jan 25 '17 16:01

Codematcha


2 Answers

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);
like image 114
T.J. Crowder Avatar answered Sep 22 '22 03:09

T.J. Crowder


I'll make an asside to @T.J. 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:

  • let and const keywords | check: caniuse.com
  • Arrow functions (=>) | check: caniuse.com
like image 45
H. Pauwelyn Avatar answered Sep 26 '22 03:09

H. Pauwelyn