附加对象值javascript

时间:2019-05-31 03:33:43

标签: javascript object vue.js vuejs2

如何附加customerApplicationAddress值否,街道,barangay,市,省,并将其放入 customerApplication.address

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

任何想法我该如何实现?我尝试循环并连接它,但不知何故出现了未定义的错误。

2 个答案:

答案 0 :(得分:1)

考虑对customApplication使用计算属性。您的代码如下:

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
      };
    }
  }
});

这样做,每次customerApplicationAddress.*基础值更改时,都会自动更新customerApplication对象。

答案 1 :(得分:1)

您似乎正在尝试将一个对象转换为键值对数组,然后转换为字符串。

您可以先使用Object.keys,然后再使用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)