torbenrudgaard
torbenrudgaard

Reputation: 2541

Adding elements to an object with multiple properties

Im pretty new working with objects, and I just cant seem to get this to work no matter how I try it.

My idea is that I want to treat printObj just like a database-table and then keep adding "records" to it. (then later "updating" the "records" and eventually loop thru all rendering them in an HTML result)

But I keep getting Uncaught TypeError: printObj.push is not a function

var printObj = new Object();

printObj.push({
    property: 'WAT-606',
    project: 'Wong Amat Tower',
    year: 2017,
    month: 1,
    bookedPct: 52
});

for (var i=0; i<10; i++) {
    var addObj = new Object();
    addObj["property"] = 'WAT-606';
    addObj["project"] = 'Wong Amat Tower';
    addObj["year"] = 2017;
    addObj["month"] = 1;
    addObj["bookedPct"] = 52+i;
    printObj.push(addObj);
}

Upvotes: 0

Views: 71

Answers (2)

trincot
trincot

Reputation: 350097

You are really looking for an array, which you create like this:

var printArr = [];

printArr.push({
    property: 'WAT-606',
    project: 'Wong Amat Tower',
    year: 2017,
    month: 1,
    bookedPct: 52
});

for (var i=0; i<10; i++) {
    var addObj = {};
    addObj.property = 'WAT-606';
    addObj.project = 'Wong Amat Tower';
    addObj.year = 2017;
    addObj.month = 1;
    addObj.bookedPct = 52+i;
    printArr.push(addObj);
}

console.log(printArr);

Upvotes: 1

RaR
RaR

Reputation: 3213

Don't do push. It is for Arrays. Directly create with properties, like

var printObj = {
    property: 'WAT-606',
    project: 'Wong Amat Tower',
    year: 2017,
    month: 1,
    bookedPct: 52
}

If you want to add additional, do like

printObj.newProp = val;

First, learn about Objects completely. This site will help you

Upvotes: 1

Related Questions