如何在循环中创build对象文字的数组?

我需要创build一个像这样的对象文字的数组:

var myColumnDefs = [ {key:"label", sortable:true, resizeable:true}, {key:"notes", sortable:true,resizeable:true},...... 

在这样的循环中:

 for ( var i=0 ; i < oFullResponse.results.length; i++) { console.log(oFullResponse.results[i].label); } 

key的值应该是数组中每个元素的results[i].label

 var arr = []; var len = oFullResponse.results.length; for (var i = 0; i < len; i++) { arr.push({ key: oFullResponse.results[i].label, sortable: true, resizeable: true }); } 

RaYell的答案很好 – 它回答你的问题。

在我看来,你应该真的创build一个以子对象为标签的标签。

 var columns = {}; for (var i = 0; i < oFullResponse.results.length; i++) { var key = oFullResponse.results[i].label; columns[key] = { sortable: true, resizeable: true }; } // Now you can access column info like this. columns['notes'].resizeable; 

上述方法应该比search整个对象数组作为每个访问的密钥要快得多和习惯。

在尼克里格斯的相同的想法,但我创build一个构造函数,并通过使用它推入一个新的对象在数组中。 它避免了重复类的关键:

 var arr = []; var columnDefs = function(key, sortable, resizeable){ this.key = key; this.sortable = sortable; this.resizeable = resizeable; }; for (var i = 0; i < len; i++) { arr.push((new columnDefs(oFullResponse.results[i].label,true,true))); } 

这将工作:

  var myColumnDefs = new Object(); for (var i = 0; i < oFullResponse.results.length; i++) { myColumnDefs[i] = ({key:oFullResponse.results[i].label, sortable:true, resizeable:true}); } 

这是Array#map擅长的

 var arr = oFullResponse.results.map(obj => ({ key: obj.label, sortable: true, resizeable: true })) 
 var myColumnDefs = new Array(); for (var i = 0; i < oFullResponse.results.length; i++) { myColumnDefs.push({key:oFullResponse.results[i].label, sortable:true, resizeable:true}); } 

我会创build数组,然后将对象文字附加到它。

 var myColumnDefs = []; for ( var i=0 ; i < oFullResponse.results.length; i++) { console.log(oFullResponse.results[i].label); myColumnDefs[myColumnDefs.length] = {key:oFullResponse.results[i].label, sortable:true, resizeable:true}; } 
Interesting Posts