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!

Luciano
  • 2,052
  • 1
  • 16
  • 26

1 Answers1

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)
})
imste
  • 360
  • 3
  • 7
  • 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? – Luciano Apr 21 '19 at 02:10