Converting an object to a string

后端 未结 30 1830
北荒
北荒 2020-11-22 03:29

How can I convert a JavaScript object into a string?

Example:

var o = {a:1, b:2}
console.log(o)
console.log(\'Item: \' + o)

Output:

相关标签:
30条回答
  • 2020-11-22 04:30

    Sure, to convert an object into a string, you either have to use your own method, such as:

    function objToString (obj) {
        var str = '';
        for (var p in obj) {
            if (obj.hasOwnProperty(p)) {
                str += p + '::' + obj[p] + '\n';
            }
        }
        return str;
    }
    

    Actually, the above just shows the general approach; you may wish to use something like http://phpjs.org/functions/var_export:578 or http://phpjs.org/functions/var_dump:604

    or, if you are not using methods (functions as properties of your object), you may be able to use the new standard (but not implemented in older browsers, though you can find a utility to help with it for them too), JSON.stringify(). But again, that won't work if the object uses functions or other properties which aren't serializable to JSON.

    0 讨论(0)
  • 2020-11-22 04:30

    If you just want to see the object for debugging, you can use

    var o = {a:1, b:2} 
    console.dir(o)
    
    0 讨论(0)
  • 2020-11-22 04:31

    In cases where you know the object is just a Boolean, Date, String, number etc... The javascript String() function works just fine. I recently found this useful in dealing with values coming from jquery's $.each function.

    For example the following would convert all items in "value" to a string:

    $.each(this, function (name, value) {
      alert(String(value));
    });
    

    More details here:

    http://www.w3schools.com/jsref/jsref_string.asp

    0 讨论(0)
  • 2020-11-22 04:31

    For non-nested objects:

    Object.entries(o).map(x=>x.join(":")).join("\r\n")
    
    0 讨论(0)
  • 2020-11-22 04:35

    If you can use lodash you can do it this way:

    > var o = {a:1, b:2};
    > '{' + _.map(o, (value, key) => key + ':' + value).join(', ') + '}'
    '{a:1, b:2}'
    

    With lodash map() you can iterate over Objects as well. This maps every key/value entry to its string representation:

    > _.map(o, (value, key) => key + ':' + value)
    [ 'a:1', 'b:2' ]
    

    And join() put the array entries together.

    If you can use ES6 Template String, this works also:

    > `{${_.map(o, (value, key) => `${key}:${value}`).join(', ')}}`
    '{a:1, b:2}'
    

    Please note this do not goes recursive through the Object:

    > var o = {a:1, b:{c:2}}
    > _.map(o, (value, key) => `${key}:${value}`)
    [ 'a:1', 'b:[object Object]' ]
    

    Like node's util.inspect() will do:

    > util.inspect(o)
    '{ a: 1, b: { c: 2 } }'
    
    0 讨论(0)
  • 2020-11-22 04:35

    For your example, I think console.log("Item:",o) would be easiest. But, console.log("Item:" + o.toString) would also work.

    Using method number one uses a nice dropdown in the console, so a long object would work nicely.

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