Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to build a javascript object using an array and the map function?

Tags:

javascript

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 ????;
});
like image 785
DanielEli Avatar asked Jun 13 '12 00:06

DanielEli


People also ask

How do you map an array into an object?

To convert an array of objects to a Map , call the map() method on the array and on each iteration return an array containing the key and value. Then pass the array of key-value pairs to the Map() constructor to create the Map object.

How do you map data from an array of objects in JavaScript?

The syntax for the map() method is as follows: arr. map(function(element, index, array){ }, this); The callback function() is called on each array element, and the map() method always passes the current element , the index of the current element, and the whole array object to it.

Can we use map on array in JavaScript?

JavaScript | Array map() MethodThe map() method in JavaScript creates an array by calling a specific function on each element present in the parent array. It is a non-mutating method. Generally map() method is used to iterate over an array and calling function on every element of array.

How do you create an object on a map?

function map(obj, callback) { var result = {}; Object. keys(obj). forEach(function (key) { result[key] = callback. call(obj, obj[key], key, obj); }); return result; } newObject = map(myObject, function(x) { return x * x; });


2 Answers

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.

like image 92
user1106925 Avatar answered Sep 20 '22 13:09

user1106925


The map function takes an array, and returns an array. Nothing else. But you can use reduce:

var settings = ["TV", "Billboard", "Spot TV"].reduce(function(obj, item) {
   obj[item.toLowerCase().replace(" ", "")] = false; // probably too concise
   return obj // yay, we can skip a semi-colon here :-P
}, {});

Well, "am not i am" beat me to it, but anyway:
map not only returns arrays, but also only returns arrays of the same length as the original. It's meant for transforming one array's values 1:1 into a new array. reduce is meant to "reduce an array to a single value". Hence its use here.

If you use a straight for loop or the forEach method to add properties to an object, you do need to declare that object. So, no, you can't do without temp in your code (unless you use reduce instead of a loop).

More information on MDN:

  1. map: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map
  2. reduce: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/Reduce
like image 31
Flambino Avatar answered Sep 18 '22 13:09

Flambino