簡體   English   中英

Node.js遍歷嵌套Javascript對象

[英]Node.js loop through nested Javascript object

我希望有來自Facebook的帖子+附件,以便創建帖子列表。 問題是我想為每個帖子提要將屬性:id,消息和任何附件放入數組中。 我不確定是否需要遍歷數組中的對象,還是可以選擇ID並獲取相關信息。

另外,我正在使用async.waterfall()來獲取同步調用,因為我將進行依賴於先前調用的其他調用。

我試圖這樣做以獲得附件的ID,消息和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的響應

而且我需要{數據-> [消息,ID,附件->數據[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_..." 
  }
}

當在getPostPicture函數中使用for循環時,i變量實際上是數組feedData的元素,因此必須使用i.idi.attachmentsi.message 我還認為,由於您在2個循環中使用相同的j ,其中一個嵌套在另一個循環中,因此它也無法正常工作,因此您可能還必須更改它,並用您期望的輸出類型向您解釋問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM