在我的对象中将循环结构转换为JSON

时间:2015-03-24 02:40:54

标签: javascript jquery json

var mapObjects = $('#placeholdSlots div').map(function (i, n) {

    var awardId = $(n).find('.dropped').attr('id');
    var itemType = $(n).find('.dropped').attr('data');

     var obj = {};
    obj['itemId'] = parseInt(awardId) || "";
    obj['type'] = itemType || ""
    return obj;

});

console.log(JSON.stringify(mapObjects));

知道为什么我不能json.stringify我的对象?最后一行返回错误

Uncaught TypeError: Converting circular structure to JSON

对我而言看起来很好:

enter image description here

我没有看到任何关于我的对象的循环引用问题..

1 个答案:

答案 0 :(得分:1)

$.fn.map()会返回jQuery个对象吗?请注意,如果在div.dropped父元素中选择#placeholdSlots div子元素,则$.map()可以迭代divdiv.dropped元素;在stacksnippets

中替换$('#placeholdSlots div:not(.dropped)')的选择器$('#placeholdSlots div')

尝试使用$.map(),返回Array



var mapObjects = $.map($("#placeholdSlots div:not(.dropped)")
                 , function (n, i) { 
                     var awardId = $(n).find(".dropped").attr("id");
                     var itemType = $(n).find(".dropped").attr("data");        
                     var obj = {};
                     obj["itemId"] = parseInt(awardId) || "";
                     obj["type"] = itemType || ""
                     return obj;        
    });
    
    console.log(JSON.stringify(mapObjects));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js">
</script>
<div id="placeholdSlots">
  <div><div id="123" class="dropped" data="abc">dropped</div></div>
  <div><div id="456" class="dropped" data="def">dropped</div></div>
</div>
&#13;
&#13;
&#13;