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 @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
=>
) | check: caniuse.com
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With