2017-07-27 39 views
0

我有兩個數組需要通過id(sourceID),這似乎已完成合並,但兩個imageTest對象返回空。現在確定我在這裏做錯了什麼?正確合併,但獲得空對象 - Javascript

我的代碼看起來是這樣的:

const eventsToBeInserted1 = [{ 
 
    name: 'Katy Perry', 
 
    slug: 'katy-perry', 
 
    sourceID: [1], 
 
    tags: ['music', 'jazz'], 
 
    images1: ['picture_perry_1', 'picture_perry_2'] 
 
    }, 
 
    { 
 
    name: 'Lukas Graham', 
 
    slug: 'lukas-graham', 
 
    sourceID: [2], 
 
    tags: ['rock', 'techno'], 
 
    images1: ['picture_graham_1', 'picture_graham_2'] 
 
    } 
 
] 
 

 
const imagesTest = [{ 
 
    sourceID: 1, 
 
    images: ['picture_perry.jpg'] 
 
    }, 
 
    { 
 
    sourceID: 2, 
 
    images: ['picture_graham.jpg'] 
 
    } 
 
] 
 

 
const eventsToBeInserted = eventsToBeInserted1.map(
 
    event => Object.assign({}, event, { 
 
    imagesTest: imagesTest 
 
     .filter(img => img.sourceID === event.sourceID) 
 
     .map(img => img.name) 
 
    })) 
 

 
console.log(eventsToBeInserted)

+0

你的問題是有點混亂。合併的概念意味着有多條記錄可以縮減爲一條記錄,但是,這似乎並不是這種情況。 sourceID是唯一的嗎?或者它實際上是1:1的關係,你只是試圖映射你的數據? – mhodges

+3

想投下來,因爲凱蒂佩裏被標記爲'爵士'(只是開玩笑,沒有投票) – Kaddath

+0

Theres沒有img.name ... –

回答

2

的問題是,在該eventsToBeInserted1sourceId被定義爲一個陣列:sourceID: [1]

要麼改變它被定義爲正INT:sourceID: 1

或改變合併功能:

const eventsToBeInserted = eventsToBeInserted1.map(
    event => Object.assign({}, event, { 
    imagesTest: imagesTest 
     .filter(img => img.sourceID === event.sourceID[0]) 
     .map(img => img.name) 
    })) 
+0

如果我理解了這個問題,我想你也想'.map(img = > event.name)' –

+1

另外,如果可能有多個源,它將是event.sourceId.indexOf(img.sourceId)... –

+0

使用上述並將其更改爲'.map(img => event.name) '完成了這項工作。感謝@fatman和@Mark_M的幫助 - 非常感謝! –