Skip to content
Advertisement

How to remove comma if there is no next value

I am merging address values in one variable like –

obj.address1 = obj.address1 + ', ' + obj.city + ', ' + obj.state + ', ' + obj.zip_code

but if there is no value in city/state/zip_code comma is showing on UI, what can i do for remove this.

Advertisement

Answer

might not be the most elegant solution but you could add the comma only if defined using the ternary operator

    const obj = {
      address1: "15th street",
      state: "NY",
      zip_code: 12345
    }
    obj.address1 = obj.address1 + ', ' + (obj.city ? obj.city + ', ' : '') + (obj.state ?   obj.state + ', ' : '') + obj.zip_code;
    console.log(obj.address1)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement