在地图函数javascript上连接字符串

时间:2019-05-31 04:36:17

标签: javascript vue.js vuejs2

我有一个对象 lengthOfStay ,在其中尝试将其中的值连接起来并放在 customerApplication.lengthOfStay

lengthOfStay:{
    yrs: '',
    mos:''
},
customerApplication: {
    length_of_stay: this.lengthOfStayYrsMos
}

computed: {
     lengthOfStayYrsMos(){
        return this.customerApplication.length_of_stay = 
        Object.keys(this.lengthOfStay).map(k =>  this.lengthOfStay[k]).join(" ")
      }
}

所以对于串联来说看起来不错,例如,结果是

lengthOfStay:{
    yrs: '2',
    mos:'2'
},
//result
customerApplication: {
    length_of_stay: "2 2"
}

如何在其上连接字符串?这样结果就是

customerApplication: {
    length_of_stay: "2 Yrs. & 2 Mos."
}

2 个答案:

答案 0 :(得分:2)

您可以使用Object.entries()从对象中获取键和值,然后将第一个字符更改为大写并以所需的格式连接

let data ={ lengthOfStay:{ yrs: '2', mos:'2' }}
let capFirstChar = (str)=> str[0].toUpperCase() + str.substr(1,)

let op = Object.entries(data.lengthOfStay)
               .map(([key, value]) => `${value} ${capFirstChar(key)}.`)
               .join(' & ')

console.log(op)

答案 1 :(得分:2)

尝试一下:

Object.keys(this.lengthOfStay).map(k =>  {
   return `${this.lengthOfStay[k]} ${k}.` 
}).join(" & ")

第一个大写字母

Object.keys(this.lengthOfStay).map(k =>  {
   return `${this.lengthOfStay[k]} ${k.charAt(0).toUpperCase() + k.slice(1)}.` 
}).join(" & ")