Converting an object to a string

后端 未结 30 1906
北荒
北荒 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: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 } }'
    

提交回复
热议问题