Search code examples
arraysreactjsecmascript-6array-merge

How to merge two arrays based on the property value in react with ES6


I have two arrays:

 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"}]

How do I get the output like this:

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

I want to merge them based on the property values: the keys "sourceId" and "targetId" of array a should correspond to the key "id" of array b. If a sourceId is matched with an id, add the value of the name with key "from" to the object in array a; If a targetId is matched with an id, add the value of the name with key "to" to the item in array a. Also,I am wondering whether I can do this without using lodash. (using ES6)


Solution

  • Convert b to a Map of id to name using Array#reduce. Then Array#map a to the required form using Object#assign, and the bMap:

    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);