Turn properties of object into a comma-separated list?

前端 未结 10 1688
-上瘾入骨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条回答
  • 2021-02-01 03:25

    Write a function like this:

    function toCSV(obj, separator) {
        var arr = [];
    
        for (var key in obj) {
            if (obj.hasOwnProperty(key)) {
                arr.push(obj[key]);
            }
        }
    
        return arr.join(separator || ",");
    }
    

    And then you can call it like:

    toCSV(person, "|"); // returns "John|Smith|253 689 4555"
    

    or

    toCSV(person); // returns "John,Smith,253 689 4555"
    
    0 讨论(0)
  • 2021-02-01 03:28

    You can use this one-liner in modern browsers

    Object.keys(person).map(function(k){return person[k]}).join(",");
    
    0 讨论(0)
  • 2021-02-01 03:31

    This code will be useful when you want to extract some property values from an array of objects as comma separated string.

        var arrayObjects = [
      {
        property1: "A",
        property2: "1"
      },
      {
        property1: "B",
        property2: "2"
      },
      {
        property1: "C",
        property2: "3"
      }
    ];
    
    Array.prototype.map.call(arrayObjects, function(item) { return item.property1; }).join(",");
    

    Output - "A,B,C"

    0 讨论(0)
  • 2021-02-01 03:33

    Another way is to use lodash function _.toString()

    console.log( _.toString( Object.values( person ) ) );
    ==> John,Smith,253 689 4555
    

    Check the link below https://lodash.com/docs/4.17.5#toString

    0 讨论(0)
提交回复
热议问题