简体   繁体   中英

Append object values javascript

How can I append the customerApplicationAddress values no, street, barangay, municipality, province and put it inside the customerApplication.address

data(){
    return {
        customerApplicationAddress: {
          no: '',
          street: '',
          barangay: '',
          municipality: '',
          province: '',
        },
        customerApplication:{
          name: null,
          address: null
        }
    }
}

Any idea how can I achieve this? I tried looping and concatenate it but somehow I'm getting an undefined error.

Consider using computed properties for customApplication . Your code would look like:

Vue.extend({
  data() {
    return {
      customerApplicationAddress: {
        no: '',
        street: '',
        barangay: '',
        municipality: '',
        province: '',
      },
      customerApplication:{
        name: null,
        address: null
      }
    };
  },

  computed: {
    customerApplication() {

      const addr = this.customerApplicationAddress;

      return {
        // Or consider using string interpolation
        address: addr.no + ' ' + addr.street + ' ' + addr.barangay + ' ' + addr.municipality + ' ' + addr.province
      };
    }
  }
});

By doing this, your customerApplication object would be automatically updated every time underlying customerApplicationAddress.* value changes.

It looks like you are trying to turn an object into an array of key value pairs & then into a string.

You can do this by using Object.keys and then Array.prototype.map .

 const data = { customerApplicationAddress: { no: '1', street: 'Big Street', barangay: 'some barangay', municipality: 'some municipality', province: 'some province', }, customerApplication:{ name: null, address: null } } data.customerApplication.address = Object.keys(data.customerApplicationAddress).map(k => data.customerApplicationAddress[k]).join(", ") console.log(data) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM