Sandeep Thomas
Sandeep Thomas

Reputation: 4727

Pushing Object into array changes existing elements in array Javascript

I'm trying to build a small quiz application and as part of it, I created a questions builder. What I'm trying is pushing all options into questions array to save corresponding options into each question.

Here is the code I'm trying

        var Question = { Questionid: 0, QuestionText: '', SectionId: 0, QuestionTime: 0, QuestionScore: 0, Mandatory: 0,Option:[] }
        var Option = { OptionId: 0, QuestionId: 0, OptionText: '', RightAnswer: '' };
        Question.Mandatory = $('#cb_mandatory').prop('checked') * -1;
        Question.Questionid = typeof ($('#div_question').data('QuestionId')) == 'undefined' ? 0 : $('#div_question').data('QuestionId');
        Question.QuestionScore = $('#txt_question_score').val();
        Question.QuestionText = $('#txt_question').val();
        Question.QuestionTime = $('#txt_question_time').val();
        Question.SectionId = $('#dd_section').val();
        //
        $('.my-options').each(function (index, item) {
            Option.OptionId = typeof ($(item).data('OptionId')) == 'undefined' ? 0 : $(item).data('OptionId');
            Option.OptionText = $(item).find('input:text').val();
            Option.QuestionId = typeof ($('#div_question').data('QuestionId')) == 'undefined' ? 0 : $('#div_question').data('QuestionId');
            Option.RightAnswer = +$(item).find(':radio').is(':checked');

            Question.Option.push(Option);
        });

        alert(JSON.stringify(Question));

Here when I checked the final alert, all the array elements are same as the last element. But when I put an alert inside the loop of each options, it looks different.

So what I guess is when changing the Options object inside the loop, those already pushed into array also gets changed.

So how can I solve this issue? I mean I need to avoid changing those already pushed into the array.

Upvotes: 0

Views: 1121

Answers (1)

Gibor
Gibor

Reputation: 1721

Objects in JavaScript are reference based. This means that what you're pushing into the array every time isn't a new Option object- it's the reference to the same Option object. When you change the object in each loop- all the ones you pushed inside also gets "changed"- actually they don't, they just point to the changed object.

What you should do is move the var Option decleration into the loop- thereby creating (and pushing) a new option object in each iteration.

Upvotes: 3

Related Questions