Home > Back-end >  Apply the keys of one object onto another with different values but identical structure
Apply the keys of one object onto another with different values but identical structure

Time:01-26

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!

CodePudding user response:

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

CodePudding user response:

From your problem statement, it seems like you want to modify keys of the obj2 and there is no need for obj1.

You can achieve that in a simple way using recursion:

function updateKeys(obj) {
   for (let key in obj) {
     const newKey = `value${key.slice(1)}`
     obj[newKey] = obj[key]
     delete obj[key]
     
     if (typeof obj[newKey] === 'object' && !Array.isArray(obj[newKey])) {
       mergeObjects(obj[newKey])
     }
   }
}
updateKeys(obj2)
  • Related