user979331
user979331

Reputation: 11961

jQuery add item to object

rough day, cant even figure out how to add an item to an object.

var holder = {};

I have tried the following to add an item to object:

function AddToHolder(questionid, customerid) {
        $(holder).extend({
            questionid: questionid,
            customerid: customerid
        });
        console.log(holder);
    }

this returns empty

 function AddToHolder(questionid, customerid) {
        holder.questionid = questionid;
        holder.customerid = customerid;
        console.log(holder);
    }

this overrides the object, so its not adding, its overriding

Upvotes: 0

Views: 114

Answers (2)

Medet Tleukabiluly
Medet Tleukabiluly

Reputation: 11940

Jquery Extend works like this

function AddToHolder(origin, questionid, customerid) {
    $.extend(origin, {
        questionid: questionid,
        customerid: customerid
    });
    console.log(origin);
}

To be aware to not override, just check if property exists

function AddToHolder(questionid, customerid) {
    if(!holder.questionid){
         //assign
    }
}

Upvotes: 1

Stryner
Stryner

Reputation: 7328

$(holder).extend is not doing exactly what you want it to. What you are doing is extending the jQuery object containing holder. For example:

var $holder = $(holder).extend({
    testing: 2
});

console.log($holder.testing); // Shows 2

If you want to extend the plain object without it being wrapped in jQuery, you can use $.extend:

// Option 1 - Modify the original object
$.extend(holder, { test: 2 });

// Option 2 - Create a new object without modifying the original
var newHolder = $.extend({}, holder, { test: 2 });

Upvotes: 1

Related Questions