Reputation: 297
How can I avoid the self
variable here?
function urlBuilder(endpoint){
var status = ["user_timeline", "home_timeline", "retweets_of_me", "show", "retweets",
"update", "update_with_media", "retweet", "unretweet", "retweeters", "lookup"
],
friendships = ["incoming", "outgoing", "create", "destroy", "update", "show"];
let endpoints = {
status: status,
friendships: friendships
}
var self = { };
endpoints[endpoint].forEach(e => {
self[e] = endpoint + "/" + e;
});
return self;
}
somewhat better, still an assignment statement.
return [{}].map(el => {
endpoints[endpoint].forEach(e => {
el[e] = endpoint + "/" + e;
});
return el;
})[0];
Upvotes: 1
Views: 129
Reputation: 135357
You could use Object.assign
too.
It does mutate the acc
but it's localized to the reduce
call.
endpoints[endpoint].reduce((acc, e) =>
Object.assign(acc, { [e]: `endpoint/${e}` }), {})
Upvotes: 1
Reputation: 664936
You cannot really. To create an object with a dynamic number of properties (and without using JSON.parse
) you always need to mutate it by assignment or something similar.
Your best bet might be
return endpoints[endpoint].reduce((self, e) => {
self[e] = endpoint + "/" + e;
return self;
}, {});
which is quite functional.
Upvotes: 4