7

I have an object:

{pm: 'val 1', dm: 'val 2', cm: 'val 3'}

and I want to loop through this and check if any of the keys are present in another object,

if they are then replace the key with the matching keys value from the other object.

{pm: 'price', dm: 'discount', cm: 'cost'}

The expected output would be:

{price: 'val 1', discount: 'val 2', cost: 'val 3'

4
  • In case they are not present in another object do you want the key/value in final object ? Commented May 17, 2019 at 3:02
  • Yeah I just realised now this is a perfect scenario where everything matches but I need it to work if say only pm is present in the first object. Commented May 17, 2019 at 3:03
  • You want the remaining key/value unchanged included in final output ? Commented May 17, 2019 at 3:05
  • The second object is going to be created manually so it will definitely have all possible matching keys. I was worried about me not passing the exact same keys in the first object but after testing one of the answers it seems to work in that scenario. Commented May 17, 2019 at 3:19

9 Answers 9

3

You can use reduce, check the existence of key in another object and than add the value from anotherObj as key in final object

let obj = {pm: 'val 1', dm: 'val 2', cm: 'val 3', 'xy':'val 4'}
let anotherObj = {pm: 'price', dm: 'discount', cm: 'cost'}

let final = Object.entries(obj).reduce((op, [key,value]) => {
  let newKey = anotherObj[key]
  op[newKey || key ] = value
  return op
},{})

console.log(final)

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

Comments

2

This is the most efficient way of doing it. Check performance of all above answers here.

var obj1 = {pm: 'val 1', dm: 'val 2', cm: 'val 3', mm: 'val 4'};
var obj2 = {pm: 'price', dm: 'discount', cm: 'cost'};
var output = {};

for(var key in obj1){
  if(obj2[key]){
    output[obj2[key]] = obj1[key];
  } else {
    output[key] = obj1[key];
  }
};

console.log(output)

1 Comment

1

Use reduce with Object.entries:

const obj1 = {pm: 'val 1', dm: 'val 2', cm: 'val 3'};
const obj2 = {pm: 'price', dm: 'discount', cm: 'cost'};
const res = Object.entries(obj1).reduce((acc, [k, v]) => ({ ...acc, [obj2[k] || k]: v }), {});
console.log(res);

Comments

1

You can convert the key object into an array using Object.entries and loop thru the array using reduce

var val = {"pm":"val 1","dm":"val 2","cm":"val 3"};
var key = {"pm":"price","dm":"discount","cm":"cost"};

var result = Object.entries(key).reduce((c, [v, k]) => Object.assign(c, {[k]: val[v] || null}), {});

console.log(result)

Comments

1

You can do that in following steps:

  • Get the entries of first object using Object.entries()
  • Use map() on the array of entries.
  • In map check if the current key is present on second object then return a entry with changed key otherwise the same one.
  • At last use Object.fromEntries() to get an object.

const obj1 = {pm: 'val 1', dm: 'val 2', cm: 'val 3'}
const obj2 = {pm: 'price', dm: 'discount', cm: 'cost'}

const res = Object.fromEntries(
                Object.entries(obj1)
                     .map(([k,v]) => [(obj2[k] || k), v])
            )

console.log(res)

Comments

1

You can achieve this with Object.keys and Array.reduce in a concise way like this:

let vals = {pm: 'val 1', dm: 'val 2', cm: 'val 3'}
let keys = {pm: 'price', dm: 'discount', cm: 'cost'}

let result = Object.keys(keys).reduce((r,k) => (r[keys[k]] = vals[k]) && r, {})

console.log(result)

Comments

1

You can access, and define the keys with obj[key] syntax. See below how the code loops through obj2, and if it matches it makes the new node on res with the value from obj2[key] as the key (res[obj2[key]]). I added an additional key mm so you can see what happens when it doesn't match.

const obj1 = {pm: 'val 1', dm: 'val 2', cm: 'val 3', mm: 'val 4'};
const obj2 = {pm: 'price', dm: 'discount', cm: 'cost'};
const res = {};

for(let key in obj1){
  if(obj2[key]){
    res[obj2[key]] = obj1[key];
  } else {
    res[key] = obj1[key];
  }
};

console.log(res);

Hope this helps!

Comments

0

You can try the code

const obj1 = {pm: 'val 1', dm: 'val 2', cm: 'val 3'},
  obj2 = {pm: 'price', dm: 'discount', cm: 'cost'},
  obj = {};
Object.keys(obj2).forEach( key2 => {
   Object.keys(obj1).forEach( key1 => {
      if (key2 === key1) {
        obj[obj2[key2]] = obj1[key1]
      }
   });
 });
console.log(obj)

This is a demo https://codepen.io/phuongnm153/pen/PvmeEN

Comments

0

A very straight forward way:

let obj = {pm: 'val 1', dm: 'val 2', cm: 'val 3'};
let otherObj = { dm: 'val 9'}

for(let key in obj){
  if(otherObj[key] != null) {
     obj[key] = otherObj[key]
  }
}

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.