Search code examples
javascriptarraysecmascript-6lodashecmascript-5

How can I merge two objects of different lengths based on the values


I have two arrays of objects, both arrays containing key,value pair. my objective is to assign key value, from one array to the second array if the string value of one key name matches the string value of another key _id.

I have tried combining the two arrays into one array and just have one array with the objects but I am still not sure how i can assign key and value to the other objects based on matching value of the key _id and name. I know how to with the same key but how do we do it based on a different key and same value? It might be bad design and practice but that's how the data is coming back. Is it doable? I have tried using lodash, spread operation, map with no success.

arr1 = [
{"_id": "electronics", "number": 35 },
{"_id": "house Appliances", "number": 5 },
{"_id": "nothing", "number":0}
]

arr2 = [
{"name": "electronics", "purpose": "entertainment", "price": 100},
{"name": "house Appliances", "purpose": "general", "price": 200},
{"name": "watches", "purpose": "time", "price": 30} ]

combinedArrObj = [
{"name": "electronics", "number": 35, "purpose": "entertainment", "price": 100},
{"name": "house Appliances", "purpose": "general", "price": 200, "number": 5}, 
{"name": "watches", "purpose": "time", "price": 30}
 ]

Solution

  • It seems to me you do not need to overcomplicate this if you only going to have one key value pair in array1. Simply convert to a map and then Array.map through array2 and Object.assign to create the merge without lodash etc.

    const arr1 = [{"_id": "electronics", "number": 35 }, {"_id": "house Appliances", "number": 5 }]
    const arr2 = [{"name": "electronics", "purpose": "entertainment", "price": 100},{"name": "house Appliances", "purpose": "general", "price": 200},{"name": "watches", "purpose": "time", "price": 30}]
    
    let map = arr1.reduce((acc, {_id, number}) => (acc[_id] = number, acc), {})
    
    let result = arr2.map(({name, ...rest}) => 
      Object.assign({ name }, rest, map[name] ? { number: map[name] } : {}))
    
    console.log(result)