问题
I need to create an array of object literals like this:
var myColumnDefs = [
{key:"label", sortable:true, resizeable:true},
{key:"notes", sortable:true,resizeable:true},......
In a loop like this:
for (var i = 0; i < oFullResponse.results.length; i++) {
console.log(oFullResponse.results[i].label);
}
The value of key
should be results[i].label
in each element of the array.
回答1:
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
});
}
回答2:
RaYell's answer is good - it answers your question.
It seems to me though that you should really be creating an object keyed by labels with sub-objects as values:
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;
The above approach should be much faster and idiomatic than searching the entire object array for a key for each access.
回答3:
This is what Array#map are good at
var arr = oFullResponse.results.map(obj => ({
key: obj.label,
sortable: true,
resizeable: true
}))
回答4:
You can do something like that in ES6.
new Array(10).fill().map((e,i) => {
return {idx: i}
});
回答5:
This will work:
var myColumnDefs = new Object();
for (var i = 0; i < oFullResponse.results.length; i++) {
myColumnDefs[i] = ({key:oFullResponse.results[i].label, sortable:true, resizeable:true});
}
回答6:
In the same idea of Nick Riggs but I create a constructor, and a push a new object in the array by using it. It avoid the repetition of the keys of the class:
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)));
}
回答7:
I'd create the array and then append the object literals to it.
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};
}
回答8:
var myColumnDefs = new Array();
for (var i = 0; i < oFullResponse.results.length; i++) {
myColumnDefs.push({key:oFullResponse.results[i].label, sortable:true, resizeable:true});
}
回答9:
If you want to go even further than @tetra with ES6 you can use the so-called "Object spread syntax" and do something like this:
let john = {
firstName: "John",
lastName: "Doe",
};
let people = new Array(10).fill().map((e, i) => {
return {
...john,
id: i
}
});
来源:https://stackoverflow.com/questions/1290131/how-to-create-an-array-of-object-literals-in-a-loop