Looking at the map
method in JavaScript, what am I doing wrong here?
// Input: [ { name: "Kevin"}, { name: "Bob" } ]
// Output: [ { "Kevin" :0 }, { "Bob": 1 } ]
var map = function(arr, property) {
var i = 0;
var m = arr.prototype.map(makeKv);
// Input: { name: "Kevin" }
// Output: { "Kevin" = i } // GLOBAL
function makeKv(item) {
return {
item: i++
};
};
console.log("m : " + m);
};
Please also help me get rid of the global, too.
There are a few issues here:
First,
var m = arr.prototype.map(makeKv);
You don't need prototype
here. You only use that when you are using the constructor, like Array.prototype.map
. Here, you just need to do arr.map
.
Second,
function makeKv(item) {
return {item: i++};
};
You never declare i
anywhere. How can you add one to something that doesn't exist. You need to have var i = 0;
before this.
Finally, return {item: i++};
will make a key called literally "item"
. You need to declare the object first (var ret = {};
), then use [item]
to set the value.
Array.map
's callback is passed the element in the array as the 1st parameter, so item
will be an object. You need to do item[property]
to get the value you want.
P.S. Don't do "m : " + m
in your console.log
, that will concat strings, thus converting m
to a string. Use ,
instead: console.log("m : ", m);
So, all together, try:
var map = function(arr, property) {
var i = 0;
var m = arr.map(makeKv);
function makeKv(item) {
var ret = {};
ret[item[property]] = i++;
return ret;
};
console.log("m : ", m);
}
DEMO: http://jsfiddle.net/FgdSj/3/
EDIT: Array.map
's callback is passed the index in the array as the 2nd parameter, so var i = 0;
isn't needed here:
var map = function(arr, property) {
var m = arr.map(makeKv);
function makeKv(item, index) {
var ret = {};
ret[item[property]] = index;
return ret;
};
console.log("m : ", m);
}