javascript - javascript - 如何使用来自另一个对象的匹配键值替换对象键

我有一个对象:

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

我想遍历这个,检查一下任何一个键是否存在于另一个对象中,

如果它们被替换,则用其他对象的匹配键值替换该键。

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

预期的输出为:

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

时间:

可以使用reduce,检查另一个对象中的键是否存在,并将anotherObj中的值作为最终对象中的键添加,


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)

这是最有效的方法,


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)

Object.entries中使用reduce


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);

你可以使用Object.entries将键对象转换为数组并使用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)

你可以使用Object.keysArray.reduce以简洁的方式实现这一点,如下所示:


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)

你可以尝试这个代码


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)



这是演示https://codepen.io/phuongnm153/pen/PvmeEN


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]


 }


}



...