So the _.map()
function in underscore doesn't return an object, but it takes them. Is there any way for it to return the exact same object it takes?
var _ = require("underscore");
var cars = {
"mom": {
"miles": "6",
"gas": "4"
},
"dad": {
"miles": "6",
"gas": "4"
}
}
var regurgitate_cars = _.map(cars, function(value, key){
return value;
});
/*
[ { miles: '6', gas: '4' }, { miles: '6', gas: '4' } ]
*/
var regurgitate_cars = _.map(cars, function(value, key){
var transfer = {};
transfer[key] = value;
return transfer;
});
/*
[ { mom: { miles: '6', gas: '4' } },
{ dad: { miles: '6', gas: '4' } } ]
*/
You can use _.object()
to turn it back into an object.
var regurgitate_cars = _.object(
_.map(cars, function(value, key){
return [key, value];
})
);
As for doing that directly with _.map
, you'd have to rewrite map to do it.
_.map()
will always return an array, but you can get the behavior with _.reduce()
:
var regurgitateCars = _.reduce(cars, function(memo, value, key) {
memo[key] = value;
return memo;
}, cars);
Note that this will modify and return the original object, if you wanted a copy you can provide an empty object as the third argument, which will be used as the memo
argument on the first call of the anonymous function:
var regurgitateCars = _.reduce(cars, function(memo, value, key) {
memo[key] = value;
return memo;
}, {});
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