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

南楼画角 提交于 2020-12-08 07:22:35

问题


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'


回答1:


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)



回答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)



回答3:


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



回答4:


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)



回答5:


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)



回答6:


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)



回答7:


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!




回答8:


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




回答9:


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]
  }
}


来源:https://stackoverflow.com/questions/56178953/how-to-replace-object-key-with-matching-key-value-from-another-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!