最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Issue with using JSON.stringify after using jQuery.map - Stack Overflow

programmeradmin5浏览0评论

I am writing a bookmarklet (that will eventually be a plugin) to scrape web pages for list items in jQuery under a specified div. I'm having an issue with using JSON.stringify

The following code allows me to convert each individual item to JSON, but has issues when using join to concatenate each string.

var dMap = $("div").filter($("#<div-id>")).find("li").map(function() {
    var iObject = {
        id: $(this).data('id'),
        text: $(this).text(),
        list_name: $(this).closest('div').attr('id')
    };
    return JSON.stringify(iObject);
});
console.log(dMap);

This second snippet of code creates each object in the array correctly, but the resulting array doesn't log the resulting JSON.

var dMap = $("div").filter($("#,div-id.")).find("li").map(function() {
    return {
        id: $(this).data('id'),
        text: $(this).text(),
        list_name: $(this).closest('div').attr('id')
    };
});
console.log(dMap);
var json = JSON.stringify(dMap);
console.log(json);

Any ideas?

I am writing a bookmarklet (that will eventually be a plugin) to scrape web pages for list items in jQuery under a specified div. I'm having an issue with using JSON.stringify

The following code allows me to convert each individual item to JSON, but has issues when using join to concatenate each string.

var dMap = $("div").filter($("#<div-id>")).find("li").map(function() {
    var iObject = {
        id: $(this).data('id'),
        text: $(this).text(),
        list_name: $(this).closest('div').attr('id')
    };
    return JSON.stringify(iObject);
});
console.log(dMap);

This second snippet of code creates each object in the array correctly, but the resulting array doesn't log the resulting JSON.

var dMap = $("div").filter($("#,div-id.")).find("li").map(function() {
    return {
        id: $(this).data('id'),
        text: $(this).text(),
        list_name: $(this).closest('div').attr('id')
    };
});
console.log(dMap);
var json = JSON.stringify(dMap);
console.log(json);

Any ideas?

Share Improve this question asked Aug 7, 2012 at 14:14 Craig DomvilleCraig Domville 353 bronze badges 1
  • As we can't see what console.log outputs, can you put the output in the question? – jeremyharris Commented Aug 7, 2012 at 14:26
Add a ment  | 

1 Answer 1

Reset to default 10

According to the documentation for .map:

As the return value is a jQuery-wrapped array, it's very mon to get() the returned object to work with a basic array.

Have you tried:

var json = JSON.stringify(dMap.get());
发布评论

评论列表(0)

  1. 暂无评论