2d array to associative array using underscore's _.map

给你一囗甜甜゛ 提交于 2019-12-11 20:32:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!