1

For my scenario, I need to push elements to an addresses array which contains objects. I'm working with vue.js.

My current working function is:

propagateCustomerInfo(selectedOption, id){

        // Propagate addresses
        this.addresses = selectedOption.addresses

        // Propagate contact's addresses
        for (var i = selectedOption.contacts.length - 1; i >= 0; i--) {
            for (var j = selectedOption.contacts[i].addresses.length - 1; j >= 0; j--) {
                let address = selectedOption.contacts[i].addresses[j]
                address.contact = selectedOption.contacts[i]
                this.addresses.push(address)
            }
        }
    },

the selectedOption object has the below structure:

{
   addresses: [
      {
         id: 0,
         street: 'My street'
      },
      {...}
   ],
   contacts: [
      {
         id: 0,
         name: 'Lorem Ipsum',
         addresses: [
            {
               id: 0,
               street: 'My street'
            },
            {...}
         ],
      }
   ]
}

Besides pushing every contact's address object to this.addresses array I need to append the contact to the address itself for multiselect rendering purposes. That's why I'm doing address.contact = selectedOption.contacts[i]

I almost sure that this can be accomplished in a prettiest way with some mapping/reduce combination but I can't figure out how to do it.

Any help will be really appreciated. Thanks!

2
  • With address.contact =, you are mutating the existing address object - are you sure that's what you want? Commented Apr 21, 2019 at 1:23
  • I didn't realize about that. Anyway it doesn't affect what I need. Thanks for the warning! Commented Apr 21, 2019 at 2:08

1 Answer 1

1

if you want to combine all address in contact variable to addresses variable:

    this.contacts.map(contact => this.addresses.push(...contact.addresses))

Edit.
to inject the contact.id and contact.name:

this.contacts.map(contact => {
  let temp = []
    contact.addresses.map(address => {
    temp.push({
      name: contact.name,
      id: contact.id,
      ...address
    })
  })
  this.addresses.push(...temp)
})
Sign up to request clarification or add additional context in comments.

1 Comment

Ok, almost done with this. Contact's addresses are being pushed to the addresses array as needed, but I also need to append the contact to every address on it. Is that possible?

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.