0

I have two objects:

let obj1 = { key1: 'someValue', key2: 'someValue2'}

let obj2 = { someValue: 'otherValue', someValue2: 'otherValue2'}

values of the obj1 is actually a key in the obj2.

I want a new object as let obj3 = { key1: 'otherValue', key2: 'otherValue2'}

I tried with Object.keys and Object.values but didn't succeed. Can you guys help me out?

3 Answers 3

2

You can use Object.keys() and array#reduce. Iterate through each keys in first object and then for each key, look up in second object to get value and put it in the result object.

const obj1 = { key1: 'someValue', key2: 'someValue2'},
      obj2 = { someValue: 'otherValue', someValue2: 'otherValue2'},
      result = Object.keys(obj1).reduce((r,k) => {
        r[k] = obj2[obj1[k]];
        return r;
      },{});
console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

1

You can use Object.entries.

let obj1 = { key1: 'someValue', key2: 'someValue2'};
let obj2 = { someValue: 'otherValue', someValue2: 'otherValue2'};

const result = {};
Object.entries(obj1).map(item => {
  result[item[0]] = obj2[item[1]];
});
console.log(result);

Comments

0

This can be achieved my mapping the keys of the targets to the config value via the target's value.

const obj1 = { key1: 'someValue', key2: 'someValue2' }
const obj2 = { someValue: 'otherValue', someValue2: 'otherValue2' }

const replaceProperties = (target, config) =>
  Object.entries(target).reduce((result, entry) =>
    (([ key, value ]) =>
      ({ ...result, [key]: config[value]  }))
    (entry), {});

console.log(replaceProperties(obj1, obj2));
.as-console-wrapper { top: 0; max-height: 100% !important; }

Code golf

As you can see above, the entire function can be expressed in one line. :)

f=(t,c)=>Object.entries(t).reduce((r,e)=>(([k,v])=>({...r,[k]:c[v]}))(e),{})
a={key1:'someValue',key2:'someValue2'}
b={someValue:'otherValue',someValue2:'otherValue2'}
console.log(f(a, b))
.as-console-wrapper { top: 0; max-height: 100% !important; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.