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'
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With