问题
I'm trying to map 2d array:
var fkOptionList2d = [[3, 'Orange'],[5, 'Banana'],[6, 'Coconut']]
to an associative array:
var fkOptionList1d = [{id: 1, label: 'Orange'},{id: 2, label: 'Banana'},{id: 3, label: 'Coconut'}]
but I'm new to underscore.js and don't quite get it yet. Should it be something like:
fkTableArr1d = _.object(_.map(fkTableArr2d, function(item, id) {
return [{"id: " + id,"label: " + item}]
}));
?
回答1:
As per my understanding you need to use
return [{
"id " : id, "label " : item
}]
instead of
return [{"id: " + id,"label: " + item}]
You are returning invalid JSON from the function
Additionally you don't need _.object
method
fkTableArr1d = _.map(fkTableArr2d, function(item, id) {
return [{
"id " : id, "label " : item
}];
});
DEMO
来源:https://stackoverflow.com/questions/19655991/2d-array-to-associative-array-using-underscores-map