Node.js遍历嵌套的Javascript对象

时间:2017-04-08 11:08:15

标签: javascript node.js javascript-objects fb-graph

我希望从Facebook上发帖子+附件,以便创建帖子列表。问题是我想为每个帖子提供属性:id,message和数组中的任何附件。我不确定是否需要迭代数组中的对象,或者我可以选择ID并获取相关信息。

此外,我正在使用async.waterfall()来获取同步调用,因为我将进行依赖于前一次调用的其他调用。

我试过这个来获取附件的id,message和src url:

var async = require("async");
var graph = require('fbgraph');

async.waterfall([
    getFeed,
    getPostPicture,
], function (err, result) {
});
function getFeed(callback) {
    graph.get("/.../feed" + "?fields=message,attachments&access_token=APPID|APPSECRET", function(err, res) {
        callback(null, res);
    });
}
function getPostPicture(arg1, callback) {

    var feedData = arg1.data;
    for(var i in feedData)
    {
        var id = feedData[i].id;
        var message = feedData[i].message;
        var feedAttachment = feedData[i].attachments

        for (var j in feedAttachment)
        {
            var attachment = feedAttachment.data;
            var attachmentURL = attachment[i].src;
            for (var j in attachmentURL)
            {
                var attachmentURL = feedAttachment.src;
            }
        }
    }
        console.log(attachment);
}

以上将输出:

[ { description: 'post message 1',
    media: { image: [Object] },
    target:
     { id: '...',
       url: 'https://www.facebook.com/.../photos/a............/.../?type=3' },
    title: 'Timeline Photos',
    type: 'photo',
    url: 'https://www.facebook.com/.../photos/a............/.../?type=3' } ]

以下是我在源代码中首次调用graph.get的响应

我需要{data - > [message,id,attachments - >数据[src]]}

{
  "data": [
    {
      "message": "post message 1",
      "id": "..._...",
      "attachments": {
        "data": [
          {
            "description": "picture 1",
            "media": {
            "image": {
            "height": 256,
            "src": "https://scontent.xx.fbcdn.net/v/t1.0-9/..._..._..._n.png?oh=...&oe=...",
            "width": 256
          }
        },
        "target": {
          "id": "...",
          "url": "https://www.facebook.com/.../photos/a............/.../?type=3"
        },
        "title": "Timeline Photos",
        "type": "photo",
        "url": "https://www.facebook.com/.../photos/a............./..../?type=3"
       }
      ]
     }
    },
    {
      "message": "Test status update 123",
      "id": "..._..."
    }
  ],
  "paging": {
  "previous": "https://graph.facebook.com/v2.8/.../feed?fields=message,attachments&format=json&since=...&access_token=...&limit=25&__paging_token=enc_...&__previous=1",
  "next": "https://graph.facebook.com/v2.8/.../feed?fields=message,attachments&format=json&access_token=...&limit=25&until=...&__paging_token=enc_..." 
  }
}

1 个答案:

答案 0 :(得分:0)

getPostPicture函数中使用for循环时,i变量实际上是数组feedData中的元素,因此您必须i.idi.attachments并且i.message。另外我认为既然你在2个循环中使用相同的j,而另一个嵌套在另一个循环中,它也不会正常工作,所以你可能也必须改变它,并解释你的问题你期待的输出。