0

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?

3
  • Why you have commented the push call? Commented Feb 26, 2014 at 16:56
  • 2
    try concat like person.phones = person.phones.concat(phoneObjs); Commented Feb 26, 2014 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 Commented Feb 26, 2014 at 17:05

1 Answer 1

3

In ES5

person.phones = person.phones.concat(phoneObjs);

In ES6:

person.phones = [...person.phones,...phoneObjs];
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That was it :) I tried push, but ended up putting Arrays inside of the phone Array instead of objects

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.