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
});
}
Answer from RaYell on Stack OverflowSo I made an array with objects. For example here, let's use people
var people = [
{
id: 0,
name: "John Doe",
age: 47
},
{
id: 1,
name: "Jane Doe",
age: 88
},
{
id: 2,
name: "Mason Louis",
age: 17
}
];
so now I can use people[1].name etc for accessing the data on each of these people. Someone just saw my code and said "That looks like total S**T".
What is the proper way to do this? I was thinking this way was fine, especially since it resembles JSON
EDIT: Would it be better to create a constructor and fill an array with instances?
javascript - How to create an array of object literals in a loop? - Stack Overflow
What is the best way to create an array of objects in Javascript? - Stack Overflow
Objects vs Arrays
Array inside a JavaScript Object? - Stack Overflow
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'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.
Creating an array is as simple as this:
var cups = [];
You can create a populated array like this:
var cups = [
{
color:'Blue'
},
{
color:'Green'
}
];
You can add more items to the array like this:
cups.push({
color:"Red"
});
MDN array documentation
The array should be like this...
var cup = [];
After we putting properties to the array, it will be like this
[
{
"color": "blue",
"size": "large",
"type": "mug"
}
]
And you can put properties like this..
var cup = [];
cup.push({
color : 'blue',
size : 'large',
type : 'mug'
})
console.log(cup);
Hello! Just curious…do you guys like manipulating objects or arrays more? Pros and cons of both?
Personally I find dot notation with objects much much easier then iteration but I am a novice and I’m curious to know if my logic is flawed.
Thanks!