Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
118
rated 0 times [  125] [ 7]  / answers: 1 / hits: 19776  / 12 Years ago, wed, june 13, 2012, 12:00:00

I've got an array of channels that I want to transform into a single object (channelSettings) with a true / false property for each channel.



I've got it working using the below code but it seems verbose. Is there are way to do it without the temp var? If I can get ride of that, then I could get ride of the self executing function as well.



var channels = [TV, Billboard, Spot TV];


var channelSettings = function() {
var temp = {};

channels.map(function(itm, i, a) {
var channel = itm.toLowerCase().replace( , );
temp[channel] = false;
});

return temp;
}();


I guess I'm trying to get the map function to return an object with properties instead of an array. Is this possible? Is it mis-guided? Suggestions?



This is what I'm hoping it looks like in the end:



var channels = [TV, Billboard, Spot TV];

var channelSettings = channels.map(function(itm, i, a) {
var channel = itm.toLowerCase().replace( , );
return ????;
});

More From » javascript

 Answers
12

Use a .reduce() function instead.



var channelSettings = channels.reduce(function(obj, itm) {
var channel = itm.toLowerCase().replace( , );
obj[channel] = false;

return obj;
}, {});


DEMO: http://jsfiddle.net/MjW9T/






The first parameter references the previously returned item, except for the first iteration, where it references either the first item in the Array, or the seeded item, which we provided as an empty object.



The second parameter references the current value in the Array. As long as we always return obj, the first parameter will always be that object, as will the final return value.


[#84950] Tuesday, June 12, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
terrence

Total Points: 120
Total Questions: 115
Total Answers: 87

Location: England
Member since Fri, May 22, 2020
4 Years ago
terrence questions
Sat, Jun 5, 21, 00:00, 3 Years ago
Wed, Jun 17, 20, 00:00, 4 Years ago
;