Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

My code below will add the last generated Object into the phones array of the Person object. What I'm trying to do is be able to add all the generated Objects into the phones array.

var person = {
    username : username,
    phones : []
}

// Added Profile
var phoneObjs   = {};
var addedPhones = $('.added_phone');

The function that loops through all the new .added_phone input values:

addedPhones.each( function(i) {
    var tag = $(this).children("label").text();
    var value = $(this).children("input").val();
    phoneObjs = $(this).map(function(i,el) {
        var $el = $(el);
        return {
            tag: tag,
            label: value
        }
    }).get();

    console.log(phoneObjs);

    person.phones = phoneObjs;
    // person.phones.push(phoneObjs);

    console.log(person.phones);
});

I'll create 2 new input fields and enter 2 different numbers, next I submit the form and run the function above. From the chrome console console.log(person.phones):

enter image description here

The 2nd time it loops around, the first Object gets replaced
enter image description here

How would you avoid this problem?

share|improve this question
    
Why you have commented the push call? –  Minko Gechev Feb 26 at 16:56
2  
try concat like person.phones = person.phones.concat(phoneObjs); –  Arun P Johny Feb 26 at 16:56
    
@MinkoGechev the push ended up creating an Array inside of an Array inside and Object. Instead of Object in Array in Object –  Leon Gaban Feb 26 at 17:05

1 Answer 1

up vote 2 down vote accepted
person.phones = person.phones.concat(phoneObjs);
share|improve this answer
    
Thanks! That was it :) I tried push, but ended up putting Arrays inside of the phone Array instead of objects –  Leon Gaban Feb 26 at 17:04

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.