Turn properties of object into a comma-separated list?

前端 未结 10 1687
-上瘾入骨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:11
    Object.values(person).join('/')
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-02-01 03:15
    var arr = [
        {
            key_1: "A",
            key_2: "1"
        },
        {
            key_1: "B",
            key_2: "2"
        },
        {
            key_1: "C",
            key_2: "3"
        }
    ];
    
    var CSVOf_arr = arr.map((item) => { return item.key_1 }).join(',')
    
    console.log('Comma seprated values of arr', CSVOf_arr)
    

    OUTPUT: A,B,C

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

    You might want to try this library - Underscore.js. It gives you really helpful methods and works across browsers.

    Here you can do it like this -

    _.values(person).join(",")
    

    or

    _.values(person).join("|")
    
    0 讨论(0)
  • 2021-02-01 03:20

    try this:

    var key,
      person = {
        name: "John",
        surname: "Smith",
        phone: "253 689 4555"
      },
      array = [];
    
    for ( key in person ) {
      if ( person.hasOwnProperty( key ) ) {
        array.push( person[ key ] );
      }
    }
    
    console.log( array.join( ',' ) );
    

    or in function style:

    var
      getValues = function ( obj ) {
        var key,
          array = [];
    
        for ( key in obj ) {
          if ( obj .hasOwnProperty( key ) ) {
            array.push( obj [ key ] );
          }
        }
    
        return obj.join( ',' );
      };
    
    var person = {
          name: "John",
          surname: "Smith",
          phone: "253 689 4555"
        };
    
    console.log( getValues( person ) );
    
    0 讨论(0)
  • 2021-02-01 03:21

    Here is a simpler one liner. It uses the Object.values() method instead of Object.keys

    Object.values(obj).join(",");
    
    0 讨论(0)
提交回复
热议问题