thormayer
thormayer

Reputation: 1070

how can I set my objects in array?

I have lots of details. I want to stack them within an array, can I do that?

detailObj = {

    textDetail: "hello this is my text!",
    id: "tooltip_businessDetails"

};

var idArray[0] = detailObg;

Upvotes: 1

Views: 85

Answers (7)

Ajay Singh Beniwal
Ajay Singh Beniwal

Reputation: 19037

instead of doing this thing use below code

var arr = [];

arr.push(detailobj);

Upvotes: 3

Christian Benseler
Christian Benseler

Reputation: 8075

detailObj = {

    textDetail: "hello this is my text!",
    id: "tooltip_businessDetails"

};

var array = [];
for(var key in detailObj) {
   array.push(detailObj[key]);
}
alert(array[0]);

Upvotes: 0

frictionlesspulley
frictionlesspulley

Reputation: 12438

Another one :

var myArray = new Array();
myArray.push(<your object>)

Upvotes: 0

VisioN
VisioN

Reputation: 145478

You can use object-oriented approach:

var detail = function(id, text) {
    this.id = id;
    this.text = text;
};

​var arr = [];
arr.push(new detail("myid", "mytext"));

console.log(arr);

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1075925

Yes:

var idArray = [
    {
        textDetail: "hello this is my text!",
        id: "tooltip_businessDetails"
    },
    {
        textDetail: "another",
        id: "anotherid"
    },
    // ...and so on
];

Or if you already have variables pointing at them:

var idArray = [detailObj, anotherDetailObj, yetAnotherDetailObj];

You can also do it dynamically after array creation:

var idArray = [];
idArray.push(detailObj);
idArray.push({
    textDetail: "another",
    id: "anotherid"
});
idArray.push(yetAnotheretailObj);

And you can do it the way you tried to, just with a slight change:

var idArray = [];
idArray[0] = detailObj;
idArray[1] = anotherDetailObj;

Any time you set an array element, the array's length property is updated to be one greater than the element you set if it isn't already (so if you set idArray[2], length becomes 3).

Note that JavaScript arrays are sparse, so you can assign to idArray[52] without creating entries for 0 through 51. In fact, JavaScript arrays aren't really arrays at all.

Upvotes: 7

Tom
Tom

Reputation: 4180

for example:

var idArray = [detailObj1, detailObj2];

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382919

I want to stack them within an array, can I do that ?

Yes you can do that. Array in JavaScript are flexible and can hold objects as well.

Example:

var myArr = [];
myArr.push(detailObj);

Upvotes: 0

Related Questions