2017-01-10 74 views
0

我在Google快訊中創建了一條警報,需要解析XML。我使用feed-reader模塊和我的代碼如下:對JSON進行迭代只會帶來最後一個結果

app.get('/', (req, res) => { 
    parse(url).then((rss) => { 
    let title, 
     link, 
     publishedDate, 
     contentSnippet = ''; 
    let json = {}; 

    rss['entries'].forEach((item) => { 
     title = item.title; 
     link = item.link.substring(42, item.link.indexOf('&ct=')); 
     publishedDate = item.publishedDate; 
     contentSnippet = item.contentSnippet; 
    }); 

    json = { 
     title, 
     link, 
     publishedDate, 
     contentSnippet 
    }; 

    res.send(beautify(json, null, 2, 100)); 
    }).catch((err) => { 
    res.send(err); 
    }); 
}); 

我要循環的關鍵"entries"裏面有什麼。雖然有效,但結果只是最後一個。

此外,如果我將json變量移動到循環內部,返回結果爲[object Object],儘管長度正確。

我試過JSON.stringify,沒什麼區別。

+0

console.log json對象在res.send之前並粘貼在這裏 –

回答

1

這個表達式最後entrie的值賦給變量:

rss['entries'].forEach((item) => { 
    title = item.title; 
    link = item.link.substring(42, item.link.indexOf('&ct=')); 
    publishedDate = item.publishedDate; 
    contentSnippet = item.contentSnippet; 
}); 

然後創建從上次值json

改爲Array#map將條目放入新數組中。每次迭代都應該返回一個對象。

const arr = rss['entries'].map(({ title, link, publishedDate, contentSnippet }) => ({ 
    title, 
    link: link.substring(42, link.indexOf('&ct=')), 
    publishedDate, 
    contentSnippet 
})); 
+0

它工作。非常感謝。 – mfgabriel92