eygrr
eygrr

Reputation: 319

How can I push data to an array within an object?

I'm not sure how I can push data to the "data" property within "decData".

        var decData = {
            labels: [],
            datasets: [

                {
                    fillColor: "rgba(151,187,205,0.5)",
                    strokeColor: "rgba(151,187,205,1)",
                    data: []
                }
            ]
        }

Here is the code I'm using that isn't working

        decData.datasets.data.push(dayProfit);

Could anyone tell me what I'm doing wrong? The error is

Uncaught TypeError: Cannot call method 'push' of undefined

Upvotes: 0

Views: 61

Answers (3)

Ibu
Ibu

Reputation: 43810

You can always add a push method to your object:

var decData = {
        ...
        push: function (value){
            this.datasets[0].data.push(value);
        }
    }

now you can use this method:

decData.push(dayProfit);

But you have have to ask yourself the question, is the first data set the only place you want to push data to? cause this is what the code does.

Upvotes: 0

Progo
Progo

Reputation: 3490

I your code, datasets is an array. Try this:

decData.datasets[0].data.push("stuff");

Good Luck!

Upvotes: 0

Mike Clark
Mike Clark

Reputation: 11959

Your datasets object is an array, so you would need to address an element within the array:

decData.datasets[0].data.push(dayProfit);

Upvotes: 1

Related Questions