Search code examples
javascriptobjectrecursion

Apply the keys of one object onto another with different values but identical structure


Given the two following objects:

const obj1 = {
   value1: 'Hello',
   value2: 'Goodbye',
   value3: ['yes', 'no'],
   value4: {
      value5: 'Phone'
   }
}

const obj2 = {
   v1: 'Orange',
   v2: 'Apple',
   v3: ['Cat', 'Dog'],
   v4: {
      v5: 'Basketball'
   }
}

How can I apply the keys of the first object onto the second object, assuming the structure/number of key/values is identical? Returning this:

{
   value1: 'Orange',
   value2: 'Apple',
   value3: ['Cat', 'Dog'],
   value4: {
      value5: 'Basketball'
   }
}

Any help would be appreciated!


Solution

  • const obj1 = {"value1":"Hello","value2":"Goodbye","value3":["yes","no"],"value4":{"value5":"Phone"}}
    const obj2 = {"v1":"Orange","v2":"Apple","v3":["Cat","Dog"],"v4":{"v5":"Basketball"}}
    
    const values = (a,b,c) => (c = Object.values(b), Object.entries(a).map(([k,v],i)=>[k,v,c[i]]))
    const f = (a,b) => (values(a,b).forEach(([k,v,v2])=>v instanceof Object ? f(v,v2) : a[k]=v2), a)
    console.log(f(structuredClone(obj1), obj2))