Turn properties of object into a comma-separated list?

前端 未结 10 1838
-上瘾入骨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"
    

提交回复
热议问题