如何用另一个对象的匹配键值替换对象键 [英] How to replace object key with matching key value from another object

查看:96
本文介绍了如何用另一个对象的匹配键值替换对象键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象:

{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'}

预期输出为:

{价格:"val 1",折扣:"val 2",成本:"val 3"

推荐答案

您可以使用 reduce ,检查另一个对象中密钥的存在,然后从 anotherObj 作为最终对象的键

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)

这篇关于如何用另一个对象的匹配键值替换对象键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆