JSON在控制台日志中作为[object object]返回

JSON returning as [object Object] in console log

本文关键字:object 返回 控制台 日志 JSON      更新时间:2023-09-26

我有点绿,你可以告诉我的帖子历史在这里,但我正试图得到一个JSON对象的键,值和它不输出,因为我认为它会。我做错了什么?

(function($){
    jQuery(document).ready(function(){
        var tableRows = [];
        var headersText = [];
        var $headers = $("th");
        var $rows = $("#table tbody tr").each(function(index) {
          $cells = $(this).find("td");
          tableRows[index] = {};
          $cells.each(function(cellIndex) {
            if(headersText[cellIndex] === undefined) {
              headersText[cellIndex] = $($headers[cellIndex]).text();
            }
            tableRows[index][headersText[cellIndex]] = $(this).text();
          });    
        });
        var tableData = {
            "tableData": tableRows
        };
        /*alert(JSON.stringify(tableData));*/
        $.each([tableData], function(key, value){
            console.log( key + ":" + value );
        });
    });
})(jQuery);

在控制台我得到:

0:[object Object]

代替(示例):

0:[NAME SAMPLE-NAME]

当一个对象被转换成字符串时会发生什么,并且将字符串和对象连接起来,对象将被转换为字符串,并且对象的字符串表示为[object Object]

console.log( key + ":" + value ); // you're concantenating strings and objects

试试这个

console.log( key, value );

作为sitenote, $.each迭代对象和数组,因此不需要将对象包装在数组中,或者将数组包装在对象中?

问题不在于console.log,而在于你的迭代。

我认为你的意思是:

 $.each(tableData["tableData"], function(key, value){
      console.log( key, value );
 });

 $.each([tableData], function(key, value){
      console.log( key, value );
 });

在您的原始代码中,您创建了一个元素- [tableData]的数组,然后迭代该数组,这实际上没有任何意义。TableData是一个散列,散列没有键和值,它有一组键和值。您需要遍历散列。