【问题标题】:Converting an object to a string将对象转换为字符串
【发布时间】:2011-08-02 12:53:42
【问题描述】:

如何将 JavaScript 对象转换为字符串?

例子:

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

输出:

Object { a=1, b=2} // 非常好的可读输出 :)
Item: [object Object] // 不知道里面是什么 :(

【问题讨论】:

  • 转成字符串有什么用?您的意思是序列化,以便以后可以从字符串构建对象?还是只是为了展示?
  • 作者已经多年不见,但请记住,多年后,我猜,问题的入口点是console.log(obj),它显示具有属性的对象,而控制台。 log('obj: '+obj) 否则会让人迷失方向。
  • 根本无法应用添加两个对象,如果我们可以这样做,值类型和引用类型将没有差异。
  • var o = {a:1, b:2}; console.log('Item:' + JSON.stringify(o))
  • 如果是控制台,我会推荐console.log("Item", obj);。不需要任何复杂的东西。

标签: javascript string object serialization tostring


【解决方案1】:

我建议使用JSON.stringify,它将对象中的变量集转换为 JSON 字符串。大多数现代浏览器本机支持此方法,但对于那些不支持的,您可以包含JS version

var obj = {
  name: 'myObj'
};

JSON.stringify(obj);

【讨论】:

  • 供参考 IE6 和 7 不支持这个。 IE6 不是什么大不了的事,因为用户很少,而且有一个积极的活动来杀死它……但是仍然有很多 IE7 用户(取决于您的用户群)。
  • 我收到“未捕获的类型错误:将循环结构转换为 JSON”。即使有循环引用,我仍然希望看到我的对象的字符串表示形式。我能做什么?
  • 如果对象有函数属性,这不起作用,例如:foo: function () {...}
  • 如果从 StackOverflow 中单击,指向 JSON 库的链接将不起作用。将其复制并粘贴到地址栏中。
  • 您可以使用JSON.stringify(obj, null, 2); 获得更漂亮的输出。
【解决方案2】:

使用javascriptString()函数

 String(yourobject); //returns [object Object]

stringify()

JSON.stringify(yourobject)

【讨论】:

  • var foo = {bar: 1};字符串(foo); ->“[对象对象]”
  • var foo = {bar: 1};字符串(foo['bar']); -> “1”
  • 如果你想要整个对象作为字符串使用 JSON.stringify(foo)
  • @VikramPote 我认为没有办法从"[object Object]".. 将对象检索到真实状态
  • JSON.stringify 并不适用于所有情况,例如按钮等输入字段的 jQuery 引用对象。
【解决方案3】:

当然,要将对象转换为字符串,要么必须使用自己的方法,例如:

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

其实上面只是展示了一般的做法;您可能希望使用 http://phpjs.org/functions/var_export:578http://phpjs.org/functions/var_dump:604 之类的东西

或者,如果您不使用方法(作为对象属性的函数),您也许可以使用新标准(但未在旧浏览器中实现,尽管您也可以找到一个实用程序来帮助他们), JSON.stringify()。但同样,如果对象使用无法序列化为 JSON 的函数或其他属性,这将不起作用。

更新

更现代的解决方案是:

function objToString (obj) {
    let str = '';
    for (const [p, val] of Object.entries(obj)) {
        str += `${p}::${val}\n`;
    }
    return str;
}

或:

function objToString (obj) {
    return Object.entries(obj).reduce((str, [p, val]) => {
        return `${str}${p}::${val}\n`;
    }, '');
}

【讨论】:

    【解决方案4】:

    使用console 保持简单,您可以只使用逗号而不是++ 将尝试将对象转换为字符串,而逗号将在控制台中单独显示。

    例子:

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

    输出:

    Object { a=1, b=2}           // useful
    Item: [object Object]        // not useful
    Item:  Object {a: 1, b: 2}   // Best of both worlds! :)
    

    参考:https://developer.mozilla.org/en-US/docs/Web/API/Console.log

    【讨论】:

    • 很好的解决方案!但是你能告诉我当你这样做时幕后会发生什么:console.log(o)?因为如果您尝试记录添加到字符串的对象,它实际上会在该对象上调用toString()
    • console.log 最终调用了称为 Printer 的东西,规范指出:“实现如何打印 args 取决于实现”——这意味着每个浏览器都可以做到这一点不同(参见 console.spec.whatwg.org/#printer )。 Firefox 会将对象显示为字符串,但颜色很好。 Chrome 会将对象显示为一个交互式组,您可以展开该组以查看属性。试试看!
    • 非常好的技巧,对于现代网络浏览器来说可能还不错,但对于所有 JS 实现来说,它并不是 100% 可靠的。例如在实现 JS 引擎的 Qt QML 中,console.log('Item: ', o); 的输出仍然是 Item: [object Object]
    • 您可以使用console.dir(o) 代替console.log 来打印javascript 对象,而不是将其打印为字符串。在开发人员工具中,这可以打开对象并检查所有属性,甚至是数组。 (见:developer.mozilla.org/de/docs/Web/API/Console/dir
    【解决方案5】:

    编辑不要使用这个答案,因为它只适用于某些版本的 Firefox。没有其他浏览器支持它。使用Gary Chambers 解决方案。

    toSource() 是您正在寻找的函数,它将以 JSON 格式输出。

    var object = {};
    object.first = "test";
    object.second = "test2";
    alert(object.toSource());
    

    【讨论】:

    • 虽然在Firefox中方便调试,但toSource()在IE中不行。
    • toSource() 不是公认的标准,因此不能保证在所有浏览器中都受支持。
    • 啊,谢谢你指出这一点。我会把我的答案留给其他不知道的人。
    • 我希望我能给你更多的支持,因为对于有 javascript 的环境来说,这是一个绝妙的解决方案(但控制台日志不方便/无法访问)。
    • 这在任何现代浏览器上根本不支持,这是怎么得到这么多赞成的?我错过了什么吗? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    【解决方案6】:

    一个选项

    console.log('Item: ' + JSON.stringify(o));

    另一种选择(正如 soktinpk 在 cmets 中指出的那样),更适合控制台调试 IMO:

    console.log('Item: ', o);

    【讨论】:

      【解决方案7】:

      这里的解决方案都不适合我。 JSON.stringify 似乎是很多人所说的,但它会削减功能,并且对于我在测试时尝试过的一些对象和数组来说似乎很糟糕。

      我制作了自己的解决方案,至少可以在 Chrome 中使用。将其发布在此处,以便在 Google 上查找此内容的任何人都可以找到它。

      //Make an object a string that evaluates to an equivalent object
      //  Note that eval() seems tricky and sometimes you have to do
      //  something like eval("a = " + yourString), then use the value
      //  of a.
      //
      //  Also this leaves extra commas after everything, but JavaScript
      //  ignores them.
      function convertToText(obj) {
          //create an array that will later be joined into a string.
          var string = [];
      
          //is object
          //    Both arrays and objects seem to return "object"
          //    when typeof(obj) is applied to them. So instead
          //    I am checking to see if they have the property
          //    join, which normal objects don't have but
          //    arrays do.
          if (typeof(obj) == "object" && (obj.join == undefined)) {
              string.push("{");
              for (prop in obj) {
                  string.push(prop, ": ", convertToText(obj[prop]), ",");
              };
              string.push("}");
      
          //is array
          } else if (typeof(obj) == "object" && !(obj.join == undefined)) {
              string.push("[")
              for(prop in obj) {
                  string.push(convertToText(obj[prop]), ",");
              }
              string.push("]")
      
          //is function
          } else if (typeof(obj) == "function") {
              string.push(obj.toString())
      
          //all other values can be done with JSON.stringify
          } else {
              string.push(JSON.stringify(obj))
          }
      
          return string.join("")
      }
      

      编辑:我知道这段代码可以改进,但一直没有去做。用户 andrey 建议改进 here 并评论:

      这里稍微改了一下代码,可以处理'null'和'undefined',也不要添加过多的逗号。

      使用它需要您自担风险,因为我根本没有验证它。随意提出任何其他改进作为评论。

      【讨论】:

      • 你缺少一些 '}'s
      • 非常漂亮的代码,但是每个对象/数组的末尾都有一个,
      • 这是最好的答案
      【解决方案8】:

      如果你只是输出到控制台,你可以使用console.log('string:', obj)。注意逗号

      【讨论】:

      • 这会在 AJAX 和 deferred 发挥作用的场景中产生问题 - 来自 console.log 的输出通常在 AJAX 完成为数组并行提供数据之后显示,这会导致到误导的结果。在这种情况下,克隆或序列化对象是可行的方法:因为我们记录了重复的对象,即使 AJAX 完成了它的工作,它也会填充“旧”数据。
      【解决方案9】:

      如果您知道对象只是布尔值、日期、字符串、数字等...javascript String() 函数可以正常工作。我最近发现这在处理来自 jquery 的 $.each 函数的值时很有用。

      例如以下将“value”中的所有项目转换为字符串:

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

      更多细节在这里:

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

      【讨论】:

      • var my_string = ''+value+'';
      • 为我工作。我更喜欢这个解决方案,因为我不会使用插件来完成这么简单的任务。
      【解决方案10】:
      var obj={
      name:'xyz',
      Address:'123, Somestreet'
       }
      var convertedString=JSON.stringify(obj) 
       console.log("literal object is",obj ,typeof obj);
       console.log("converted string :",convertedString);
       console.log(" convertedString type:",typeof convertedString);
      

      【讨论】:

        【解决方案11】:

        现有答案中实际上缺少一个简单的选项(对于最近的浏览器和 Node.js):

        console.log('Item: %o', o);
        

        我更喜欢这个,因为JSON.stringify() 有一定的局限性(例如,具有圆形结构)。

        【讨论】:

          【解决方案12】:

          我一直在寻找这个,并写了一个带有缩进的深度递归:

          function objToString(obj, ndeep) {
            if(obj == null){ return String(obj); }
            switch(typeof obj){
              case "string": return '"'+obj+'"';
              case "function": return obj.name || obj.toString();
              case "object":
                var indent = Array(ndeep||1).join('\t'), isArray = Array.isArray(obj);
                return '{['[+isArray] + Object.keys(obj).map(function(key){
                     return '\n\t' + indent + key + ': ' + objToString(obj[key], (ndeep||1)+1);
                   }).join(',') + '\n' + indent + '}]'[+isArray];
              default: return obj.toString();
            }
          }
          

          用法:objToString({ a: 1, b: { c: "test" } })

          【讨论】:

          【解决方案13】:

          如果你只想查看对象进行调试,可以使用

          var o = {a:1, b:2} 
          console.dir(o)
          

          【讨论】:

            【解决方案14】:

            1.

            JSON.stringify(o);
            

            项目:{"a":"1", "b":"2"}

            2.

            var o = {a:1, b:2};
            var b=[]; Object.keys(o).forEach(function(k){b.push(k+":"+o[k]);});
            b="{"+b.join(', ')+"}";
            console.log('Item: ' + b);
            

            项目:{a:1, b:2}

            【讨论】:

            • 如果您考虑添加有关您的答案的更多详细信息会更好。
            【解决方案15】:

            似乎 JSON 接受了第二个可以帮助函数的参数 - replacer,这以最优雅的方式解决了转换问题:

            JSON.stringify(object, (key, val) => {
                if (typeof val === 'function') {
                  return String(val);
                }
                return val;
              });
            

            【讨论】:

              【解决方案16】:

              JSON 方法远不如 Gecko 引擎 .toSource() 原语。

              请参阅SO article response 进行比较测试。

              另外,answer above 指的是 http://forums.devshed.com/javascript-development-115/tosource-with-arrays-in-ie-386109.html,它与 JSON 一样(另一篇文章 http://www.davidpirek.com/blog/object-to-string-how-to-deserialize-json 通过 "ExtJs JSON encode source code" 使用)无法处理循环引用并且不完整。下面的代码显示了它的(恶搞)限制(更正以处理没有内容的数组和对象)。

              (direct link to code in //forums.devshed.com/ ... /tosource-with-arrays-in-ie-386109)

              javascript:
              Object.prototype.spoof=function(){
                  if (this instanceof String){
                    return '(new String("'+this.replace(/"/g, '\\"')+'"))';
                  }
                  var str=(this instanceof Array)
                      ? '['
                      : (this instanceof Object)
                          ? '{'
                          : '(';
                  for (var i in this){
                    if (this[i] != Object.prototype.spoof) {
                      if (this instanceof Array == false) {
                        str+=(i.match(/\W/))
                            ? '"'+i.replace('"', '\\"')+'":'
                            : i+':';
                      }
                      if (typeof this[i] == 'string'){
                        str+='"'+this[i].replace('"', '\\"');
                      }
                      else if (this[i] instanceof Date){
                        str+='new Date("'+this[i].toGMTString()+'")';
                      }
                      else if (this[i] instanceof Array || this[i] instanceof Object){
                        str+=this[i].spoof();
                      }
                      else {
                        str+=this[i];
                      }
                      str+=', ';
                    }
                  };
                  str=/* fix */(str.length>2?str.substring(0, str.length-2):str)/* -ed */+(
                      (this instanceof Array)
                      ? ']'
                      : (this instanceof Object)
                          ? '}'
                          : ')'
                  );
                  return str;
                };
              for(i in objRA=[
                  [   'Simple Raw Object source code:',
                      '[new Array, new Object, new Boolean, new Number, ' +
                          'new String, new RegExp, new Function, new Date]'   ] ,
              
                  [   'Literal Instances source code:',
                      '[ [], {}, true, 1, "", /./, function(){}, new Date() ]'    ] ,
              
                  [   'some predefined entities:',
                      '[JSON, Math, null, Infinity, NaN, ' +
                          'void(0), Function, Array, Object, undefined]'      ]
                  ])
              alert([
                  '\n\n\ntesting:',objRA[i][0],objRA[i][1],
                  '\n.toSource()',(obj=eval(objRA[i][1])).toSource(),
                  '\ntoSource() spoof:',obj.spoof()
              ].join('\n'));
              

              其中显示:

              testing:
              Simple Raw Object source code:
              [new Array, new Object, new Boolean, new Number, new String,
                        new RegExp, new Function, new Date]
              
              .toSource()
              [[], {}, (new Boolean(false)), (new Number(0)), (new String("")),
                        /(?:)/, (function anonymous() {}), (new Date(1303248037722))]
              
              toSource() spoof:
              [[], {}, {}, {}, (new String("")),
                        {}, {}, new Date("Tue, 19 Apr 2011 21:20:37 GMT")]
              

              testing:
              Literal Instances source code:
              [ [], {}, true, 1, "", /./, function(){}, new Date() ]
              
              .toSource()
              [[], {}, true, 1, "", /./, (function () {}), (new Date(1303248055778))]
              
              toSource() spoof:
              [[], {}, true, 1, ", {}, {}, new Date("Tue, 19 Apr 2011 21:20:55 GMT")]
              

              testing:
              some predefined entities:
              [JSON, Math, null, Infinity, NaN, void(0), Function, Array, Object, undefined]
              
              .toSource()
              [JSON, Math, null, Infinity, NaN, (void 0),
                     function Function() {[native code]}, function Array() {[native code]},
                            function Object() {[native code]}, (void 0)]
              
              toSource() spoof:
              [{}, {}, null, Infinity, NaN, undefined, {}, {}, {}, undefined]
              

              【讨论】:

                【解决方案17】:

                对于非嵌套对象:

                Object.entries(o).map(x=>x.join(":")).join("\r\n")
                

                【讨论】:

                  【解决方案18】:

                  stringify-object是yeoman团队制作的一个不错的npm库:https://www.npmjs.com/package/stringify-object

                  npm install stringify-object
                  

                  然后:

                  const stringifyObject = require('stringify-object');
                  stringifyObject(myCircularObject);
                  

                  显然,只有当你有循环对象会因JSON.stringify(); 而失败时,这才有趣

                  【讨论】:

                  • 为什么有人会使用 NPM 模块来完成这样的事情,而这可以通过纯 JS 中的单行来实现?这个答案需要详细说明为什么有人会这样做。
                  • 通常,在边缘情况下,lib 会有所帮助。我用它来处理循环引用。
                  • 添加关于圆形对象的注释更有意义,消除了我的反对意见。
                  【解决方案19】:

                  由于 firefox 不会将某些对象字符串化为屏幕对象;如果您想获得相同的结果,例如:JSON.stringify(obj)

                  function objToString (obj) {
                      var tabjson=[];
                      for (var p in obj) {
                          if (obj.hasOwnProperty(p)) {
                              tabjson.push('"'+p +'"'+ ':' + obj[p]);
                          }
                      }  tabjson.push()
                      return '{'+tabjson.join(',')+'}';
                  }
                  

                  【讨论】:

                    【解决方案20】:

                    如果你只关心字符串、对象和数组:

                    function objectToString (obj) {
                            var str = '';
                            var i=0;
                            for (var key in obj) {
                                if (obj.hasOwnProperty(key)) {
                                    if(typeof obj[key] == 'object')
                                    {
                                        if(obj[key] instanceof Array)
                                        {
                                            str+= key + ' : [ ';
                                            for(var j=0;j<obj[key].length;j++)
                                            {
                                                if(typeof obj[key][j]=='object') {
                                                    str += '{' + objectToString(obj[key][j]) + (j > 0 ? ',' : '') + '}';
                                                }
                                                else
                                                {
                                                    str += '\'' + obj[key][j] + '\'' + (j > 0 ? ',' : ''); //non objects would be represented as strings
                                                }
                                            }
                                            str+= ']' + (i > 0 ? ',' : '')
                                        }
                                        else
                                        {
                                            str += key + ' : { ' + objectToString(obj[key]) + '} ' + (i > 0 ? ',' : '');
                                        }
                                    }
                                    else {
                                        str +=key + ':\'' + obj[key] + '\'' + (i > 0 ? ',' : '');
                                    }
                                    i++;
                                }
                            }
                            return str;
                        }
                    

                    【讨论】:

                      【解决方案21】:

                      也许你正在寻找

                      JSON.stringify(JSON.stringify(obj))
                      
                      
                      "{\"id\":30}"
                      

                      【讨论】:

                        【解决方案22】:

                        看看jQuery-JSON插件

                        它的核心是使用 JSON.stringify,但如果浏览器没有实现它,它会退回到它自己的解析器。

                        【讨论】:

                          【解决方案23】:

                          如果你可以使用 lodash,你可以这样做:

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

                          使用 lodash map() 您也可以迭代对象。 这会将每个键/值条目映射到其字符串表示形式:

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

                          然后join() 将数组条目放在一起。

                          如果你可以使用 ES6 模板字符串,这也可以:

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

                          请注意,这不会通过对象递归:

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

                          就像node's util.inspect() 一样:

                          > util.inspect(o)
                          '{ a: 1, b: { c: 2 } }'
                          

                          【讨论】:

                            【解决方案24】:
                            function objToString (obj) {
                                var str = '{';
                                if(typeof obj=='object')
                                  {
                            
                                    for (var p in obj) {
                                      if (obj.hasOwnProperty(p)) {
                                          str += p + ':' + objToString (obj[p]) + ',';
                                      }
                                  }
                                }
                                  else
                                  {
                                     if(typeof obj=='string')
                                      {
                                        return '"'+obj+'"';
                                      }
                                      else
                                      {
                                        return obj+'';
                                      }
                                  }
                            
                            
                            
                                return str.substring(0,str.length-1)+"}";
                            }
                            

                            【讨论】:

                              【解决方案25】:
                              var o = {a:1, b:2};
                              
                              o.toString=function(){
                                return 'a='+this.a+', b='+this.b;
                              };
                              
                              console.log(o);
                              console.log('Item: ' + o);
                              

                              由于 Javascript v1.0 可以在任何地方使用(甚至 IE) 这是一种本机方法,允许在调试和生产时对您的对象进行非常个性化的外观 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/toString

                              有用的例子

                              var Ship=function(n,x,y){
                                this.name = n;
                                this.x = x;
                                this.y = y;
                              };
                              Ship.prototype.toString=function(){
                                return '"'+this.name+'" located at: x:'+this.x+' y:'+this.y;
                              };
                              
                              alert([new Ship('Star Destroyer', 50.001, 53.201),
                              new Ship('Millennium Falcon', 123.987, 287.543),
                              new Ship('TIE fighter', 83.060, 102.523)].join('\n'));//now they can battle!
                              //"Star Destroyer" located at: x:50.001 y:53.201
                              //"Millennium Falcon" located at: x:123.987 y:287.543
                              //"TIE fighter" located at: x:83.06 y:102.523
                              

                              另外,作为奖励

                              function ISO8601Date(){
                                return this.getFullYear()+'-'+(this.getMonth()+1)+'-'+this.getDate();
                              }
                              var d=new Date();
                              d.toString=ISO8601Date;//demonstrates altering native object behaviour
                              alert(d);
                              //IE6   Fri Jul 29 04:21:26 UTC+1200 2016
                              //FF&GC Fri Jul 29 2016 04:21:26 GMT+1200 (New Zealand Standard Time)
                              //d.toString=ISO8601Date; 2016-7-29
                              

                              【讨论】:

                                【解决方案26】:

                                循环引用

                                通过使用下面的replacer,我们可以产生更少的冗余 JSON - 如果源对象包含对某个对象的多重引用,或者包含循环引用 - 然后我们通过特殊的路径字符串引用它(类似于 JSONPath) - 我们如下使用它

                                let s = JSON.stringify(obj, refReplacer());
                                

                                function refReplacer() {
                                  let m = new Map(), v= new Map(), init = null;
                                
                                  return function(field, value) {
                                    let p= m.get(this) + (Array.isArray(this) ? `[${field}]` : '.' + field); 
                                    let isComplex= value===Object(value)
                                    
                                    if (isComplex) m.set(value, p);  
                                    
                                    let pp = v.get(value)||'';
                                    let path = p.replace(/undefined\.\.?/,'');
                                    let val = pp ? `#REF:${pp[0]=='[' ? '$':'$.'}${pp}` : value;
                                    
                                    !init ? (init=value) : (val===init ? val="#REF:$" : 0);
                                    if(!pp && isComplex) v.set(value, path);
                                   
                                    return val;
                                  }
                                }
                                
                                
                                
                                
                                // ---------------
                                // TEST
                                // ---------------
                                
                                // gen obj with duplicate references
                                let a = { a1: 1, a2: 2 };
                                let b = { b1: 3, b2: "4" };
                                let obj = { o1: { o2:  a  }, b, a }; // duplicate reference
                                a.a3 = [1,2,b];                      // circular reference
                                b.b3 = a;                            // circular reference
                                
                                
                                let s = JSON.stringify(obj, refReplacer(), 4);
                                
                                console.log(s);

                                奖励:这是这种序列化的反函数

                                function parseRefJSON(json) {
                                  let objToPath = new Map();
                                  let pathToObj = new Map();
                                  let o = JSON.parse(json);
                                  
                                  let traverse = (parent, field) => {
                                    let obj = parent;
                                    let path = '#REF:$';
                                
                                    if (field !== undefined) {
                                      obj = parent[field];
                                      path = objToPath.get(parent) + (Array.isArray(parent) ? `[${field}]` : `${field?'.'+field:''}`);
                                    }
                                
                                    objToPath.set(obj, path);
                                    pathToObj.set(path, obj);
                                    
                                    let ref = pathToObj.get(obj);
                                    if (ref) parent[field] = ref;
                                
                                    for (let f in obj) if (obj === Object(obj)) traverse(obj, f);
                                  }
                                  
                                  traverse(o);
                                  return o;
                                }
                                
                                
                                
                                // ------------
                                // TEST
                                // ------------
                                
                                let s = `{
                                    "o1": {
                                        "o2": {
                                            "a1": 1,
                                            "a2": 2,
                                            "a3": [
                                                1,
                                                2,
                                                {
                                                    "b1": 3,
                                                    "b2": "4",
                                                    "b3": "#REF:$.o1.o2"
                                                }
                                            ]
                                        }
                                    },
                                    "b": "#REF:$.o1.o2.a3[2]",
                                    "a": "#REF:$.o1.o2"
                                }`;
                                
                                console.log('Open Chrome console to see nested fields:');
                                let obj = parseRefJSON(s);
                                
                                console.log(obj);

                                【讨论】:

                                  【解决方案27】:
                                  /*
                                      This function is as JSON.Stringify (but if you has not in your js-engine you can use this)
                                      Params:
                                          obj - your object
                                          inc_ident - can be " " or "\t".
                                          show_types - show types of object or not
                                          ident - need for recoursion but you can not set this parameter.
                                  */
                                  function getAsText(obj, inc_ident, show_types, ident) {
                                      var res = "";
                                      if (!ident)
                                          ident = "";
                                      if (typeof(obj) == "string") {
                                          res += "\"" + obj + "\" ";
                                          res += (show_types == true) ? "/* typeobj: " + typeof(obj) + "*/" : "";
                                      } else if (typeof(obj) == "number" || typeof(obj) == "boolean") {
                                          res += obj;
                                          res += (show_types == true) ? "/* typeobj: " + typeof(obj) + "*/" : "";
                                      } else if (obj instanceof Array) {
                                          res += "[ ";
                                          res += show_types ? "/* typeobj: " + typeof(obj) + "*/" : "";
                                          res += "\r\n";
                                          var new_ident = ident + inc_ident;
                                          var arr = [];
                                          for(var key in obj) {
                                              arr.push(new_ident + getAsText(obj[key], inc_ident, show_types, new_ident));
                                          } 
                                          res += arr.join(",\r\n") + "\r\n";
                                          res += ident + "]";
                                      } else {
                                          var new_ident = ident + inc_ident;      
                                          res += "{ ";
                                          res += (show_types == true) ? "/* typeobj: " + typeof(obj) + "*/" : "";
                                          res += "\r\n";
                                          var arr = [];
                                          for(var key in obj) {
                                              arr.push(new_ident + '"' + key + "\" : " + getAsText(obj[key], inc_ident, show_types, new_ident));
                                          }
                                          res += arr.join(",\r\n") + "\r\n";
                                          res += ident + "}\r\n";
                                      } 
                                      return res;
                                  };
                                  

                                  使用示例:

                                  var obj = {
                                      str : "hello",
                                      arr : ["1", "2", "3", 4],
                                  b : true,
                                      vobj : {
                                          str : "hello2"
                                      }
                                  }
                                  
                                  var ForReading = 1, ForWriting = 2;
                                  var fso = new ActiveXObject("Scripting.FileSystemObject")
                                  f1 = fso.OpenTextFile("your_object1.txt", ForWriting, true)
                                  f1.Write(getAsText(obj, "\t"));
                                  f1.Close();
                                  
                                  f2 = fso.OpenTextFile("your_object2.txt", ForWriting, true)
                                  f2.Write(getAsText(obj, "\t", true));
                                  f2.Close();
                                  

                                  your_object1.txt:

                                  { 
                                      "str" : "hello" ,
                                      "arr" : [ 
                                          "1" ,
                                          "2" ,
                                          "3" ,
                                          4
                                      ],
                                      "b" : true,
                                      "vobj" : { 
                                          "str" : "hello2" 
                                      }
                                  
                                  }
                                  

                                  your_object2.txt:

                                  { /* typeobj: object*/
                                      "str" : "hello" /* typeobj: string*/,
                                      "arr" : [ /* typeobj: object*/
                                          "1" /* typeobj: string*/,
                                          "2" /* typeobj: string*/,
                                          "3" /* typeobj: string*/,
                                          4/* typeobj: number*/
                                      ],
                                      "b" : true/* typeobj: boolean*/,
                                      "vobj" : { /* typeobj: object*/
                                          "str" : "hello2" /* typeobj: string*/
                                      }
                                  
                                  }
                                  

                                  【讨论】:

                                  • 它会很好地解释代码的作用以及如何使用它的示例。谢谢
                                  【解决方案28】:

                                  对于你的例子,我认为 console.log("Item:",o) 将是最简单的。但, console.log("Item:" + o.toString) 也可以。

                                  使用方法一会在控制台中使用漂亮的下拉菜单,因此长对象会很好地工作。

                                  【讨论】:

                                    【解决方案29】:

                                    我希望这个例子对所有正在处理对象数组的人有所帮助

                                    var data_array = [{
                                                        "id": "0",
                                                        "store": "ABC"
                                                    },{
                                                        "id":"1",
                                                        "store":"XYZ"
                                                    }];
                                    console.log(String(data_array[1]["id"]+data_array[1]["store"]));
                                    

                                    【讨论】:

                                      【解决方案30】:

                                      如果你不想将 join() 播放到 Object。

                                      const obj = {one:1, two:2, three:3};
                                      let arr = [];
                                      for(let p in obj)
                                          arr.push(obj[p]);
                                      const str = arr.join(',');
                                      

                                      【讨论】:

                                        猜你喜欢
                                        • 2014-01-14
                                        • 2016-06-10
                                        • 2022-01-20
                                        • 1970-01-01
                                        相关资源
                                        最近更新 更多