Search code examples
arraysreplacelodash

Lodash Two Arrays Replace Values


I am trying to use lodash to replace the value in one array object from another array object when a common value matches.

array1 = [{
  "internalid": "1233",
  "entity": "1141",
  "items": [{
    "lineuniquekey": "20000",
    "item": "118",
    "drate": "33.75"
  }, {
    "lineuniquekey": "43964",
    "item": "122",
    "drate": "33.75"
  }, {
    "lineuniquekey": "43974",
    "item": "106",
    "drate": "0.00"
  }]
}]

array1 = [{
  "internalid": "1",
  "iname": "SW-CAL-1",
  "item": "106",
  "srate": "30.00"
}];

For example, if "item" in array1 matches "item" in array2 then update "drate" in array1 with "srate" from array2.

I looked at this but it doesn't really replace the value in the first array from a value of a second.


Solution

  • Create a Map of item -> srate from array2. Iterate array1 (the entities) with Array.map(). Grab the items array from the entity, and map the items. For each item check if it exists in the Map. If it does, replace it's drate with the value from the Map. If not return the original item:

    const array1 = [{"internalid":"1233","entity":"1141","items":[{"lineuniquekey":"20000","item":"118","drate":"33.75"},{"lineuniquekey":"43964","item":"122","drate":"33.75"},{"lineuniquekey":"43974","item":"106","drate":"0.00"}]}]
    const array2 = [{"internalid":"1","iname":"SW-CAL-1","item":"106","srate":"30.00"}]
    
    const arr2Map = new Map(array2.map(o => [o.item, o.srate]))
    
    const mapEntityItems = ({ items, ...rest }) => ({
      ...rest,
      items: items.map(o => arr2Map.has(o.item) ? ({ 
        ...o,
        drate: arr2Map.get(o.item) 
      }) : o)
    })
    
    const result = array1.map(mapEntityItems)
    
    console.log(result)