-2

I'm trying to update an existing JavaScript object with a new key value and also update an existing value like so

$.each(eventsData, function() {
    if (this.ID== "eb_0") {
        this.push({
            author_name: "John Seeds" //new key value pair to be added.
            title: newTitle_var //to be updated
        });
    }
});
console.log(this.eventsData)  

My Object looks something like this.

[
    Object { ID="eb_0", title="DayY", Date=Date, more...}, 
    Object { ID="eb_1", title="DayZ", Date=Date, more...},
    Object { ID="eb_2", title="DayX", Date=Date, more...}          
]

Currently console.log outputs the following error.

Uncaught TypeError: Object #<Object> has no method 'push' 

Could anyone help me figure this out please?

icktoofay
  • 126,289
  • 21
  • 250
  • 231
BaconJuice
  • 3,739
  • 13
  • 56
  • 88
  • 1
    You should use a variable instead of `this` because `push()` works with array object. – Dhaval Marthak May 16 '14 at 15:41
  • 1
    it appears that `this` isn't what you are expecting it to be. Also, your object is actually an array. – forgivenson May 16 '14 at 15:41
  • possible duplicate of [Javascript Object push() function](http://stackoverflow.com/questions/8925820/javascript-object-push-function) – Ejaz May 16 '14 at 16:51
  • @Ejay: Considering the accepted answer, it turns out `push` wasn't necessary at all, so the suggested duplicate is not helpful. – icktoofay May 17 '14 at 06:08
  • the expected output of both problems looked a lot alike to me. I've retracted the vote :) – Ejaz May 17 '14 at 08:33

1 Answers1

3

You could use:

$.each(eventsData, function () {
    if (this.ID == "eb_0") {
        this.author_name = "John Seeds"; //new key value pair to be added.
        this.title = newTitle_var; //to be updated
    }
});
A. Wolff
  • 74,033
  • 9
  • 94
  • 155