Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace object key with matching key value from another object

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'

like image 615
UXCODA Avatar asked May 17 '19 02:05

UXCODA


2 Answers

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)
like image 121
Code Maniac Avatar answered Oct 24 '22 10:10

Code Maniac


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)
like image 2
hashed_name Avatar answered Oct 24 '22 11:10

hashed_name