将简单数组转换为对象数组

时间:2015-03-23 19:30:12

标签: javascript underscore.js

将前者转换为后者的最简单方法是什么?

var simpleArray = [1,1,2,3,5,8,13,21];


var objArray = [{ tag : 1}, { tag : 1},{ tag : 2}, { tag : 3},
                { tag : 5}, { tag : 8},{ tag : 13},{ tag : 21}];

1 个答案:

答案 0 :(得分:4)

无需下划线。您可以使用vanilla javascript轻松完成此操作:



var i, tag, main, simpleArray = [1,1,2,3,5,8,13,21];

var complexArray = simpleArray.map(function(e) { return { tag: e }; });

main = document.getElementById('main');

for(i = 0; i < complexArray.length; i++) {
  tag = complexArray[i];
  main.innerHTML += '<div>tag: '+tag.tag+'</div>';
}
&#13;
<div id='main'></div>
&#13;
&#13;
&#13;