Turn properties of object into a comma-separated list?

前端 未结 10 1715
-上瘾入骨i
-上瘾入骨i 2021-02-01 02:42

I have an object like this:

var person = {
  name: \"John\",
  surname: \"Smith\",
  phone: \"253 689 4555\"
}

I want:



        
10条回答
  •  旧时难觅i
    2021-02-01 03:12

    The Object.values() method returns an array of a given object's own enumerable property values. It can be used to convert object properties to an array which can then be joined using .join(separator) to create the required string with separator defined in join function. But this will cause empty values to be joined as well. So for an object as

    var person = {
      name: "John",
      surname: "Smith",
      phone: ""
    }
    

    output for

    Object.values(person).join(',')
    

    will be

    John,Smith,

    with an additional "," at the end. To avoid this .filter() can be used to remove empty elements from array and then use join on filtered array.

    Object.values(person).filter(Boolean).join(',')
    

    will output

    John,Smith

提交回复
热议问题