2017-09-01 116 views
0

反應我有兩個數組:如何合併基於屬性值的兩個數組與ES6

a = [{"sourceId": "1", "targetId": "2", "name": "heats air"} , 
     {"sourceId": "3", "targetId": "4", "name": "power"}] 

b = [{"name": "Hair Dryer", "id": "1"}, 
     {"name": "Heating System", "id": "2"}, 
     {"name": "Mains", "id": "3"}, 
     {"name": "Blower", "id": "4"}] 

如何得到的輸出是這樣的:

[{"sourceId": "1", "targetId": "2", "name": "heats air", "from": "Hair Dryer", "to": "Heating System"}, 
{"sourceId": "3", "targetId": "4", "name": "power","from": "Mains", "to": "Blower"] 

我想將它們合併基於屬性值:數組a的鍵「sourceId」和「targetId」應該對應於數組b的鍵「id」。如果一個sourceId與一個id相匹配,那麼將該名稱的值用鍵「from」添加到數組a中的對象中;如果一個targetId與一個id相匹配,那麼將該名稱的值加上「to」鍵到數組a中的項目。另外,我想知道我是否可以在不使用lodash的情況下做到這一點。 (使用ES6)

+1

目前尚不清楚合併算法應該是爲得到合併的對象沒有公共屬性。你如何確定與什麼合併?請描述「以合適的方式」合併算法。而且,你如何確定應該設置什麼'from'和'to'? – jfriend00

+0

數組a的鍵「sourceId」和「targetId」應該對應數組b的鍵「id」。 – hypha

+0

請編輯您的問題,將合併算法添加到您的問題。同時描述應該如何設置'from'和'to'。評論不應該用於所需的信息 - 該信息應該添加到問題本身。 – jfriend00

回答

1

使用Array#reduce轉換b到的id一個Mapname。然後Array#mapa所要求的形式使用Object#assignbMap

const a = [{"sourceId":"1","targetId":"2","name":"heats air"},{"sourceId":"3","targetId":"4","name":"power"}]; 
 

 
const b = [{"name":"Hair Dryer","id":"1"},{"name":"Heating System","id":"2"},{"name":"Mains","id":"3"},{"name":"Blower","id":"4"}]; 
 

 
const bMap = b.reduce((map, item) => map.set(item.id, item.name), new Map); 
 

 
const result = a.map((item) => (Object.assign({ 
 
    from: bMap.get(item.sourceId), 
 
    to: bMap.get(item.targetId) 
 
}, item))); 
 

 
console.log(result);

-1

AB [索引] = Object.assign(一個[索引],B [指數])

+0

這不會產生所需的結果。請注意,結果中添加了新的屬性,如「from」和「to」。 – jfriend00

+0

這假設兩個陣列的長度和順序是相同的。 – lux

0

在這裏你去。

const a = [{"sourceId": "1", "targetId": "2", "name": "heats air"} , 
 
     {"sourceId": "3", "targetId": "4", "name": "power"}] 
 

 
const b = [{"name": "Hair Dryer", "id": "1"}, 
 
     {"name": "Heating System", "id": "2"}, 
 
     {"name": "Mains", "id": "3"}, 
 
     {"name": "Blower", "id": "4"}] 
 
     
 
const result = a.reduce((arr, curr) => { 
 
    \t const from = b.filter(bObj => { 
 
    \t return bObj.id === curr.sourceId; 
 
    })[0] 
 
    const to = b.filter(bObj => { 
 
    \t return bObj.id === curr.targetId; 
 
    })[0]; 
 
    arr.push({ ...curr, from: from.name, to: to.name }); 
 
    return arr; 
 
}, []); 
 
    
 
console.log(result);