tiltol
tiltol

Reputation: 11

change object key based on other object value

I am trying to change object key name by comparing two objects values. if the value of second object matches the first object I want to get the key name of the second object and change the first object key name to be the same. Here is the code I have but it fails to replace the key name of parsedCodedParms to mappingParms

for (var [key, value] of Object.entries(parsedCodedParams)) {
  for (var [k, v] of Object.entries(this.mappingParams)) {
    if (v.toLowerCase() == key) {
      parsedCodedParams[key] = this.mappingParams[k];
      console.log(parsedCodedParams[key])
    }
  }
}

Example:

parsedCodedParams = {a: "1",b:"2", c: "3"} 
mappingParams={ d:"1",z:"5"} 

should result

parsedCodedParams= {d: "1",b:"2", c: "3"} 

Upvotes: 1

Views: 223

Answers (2)

user120242
user120242

Reputation: 15268

Using reduce. Generates a map of values, merges the values as keys, discards the key and converts back to map. Added version that preserves order of keys.

parsedCodedParams = {a: "a",b:"2", c: "3"} 
mappingParams={ d:"A",z:"5"} 

// does not preserve order of parsedCodedParams
console.log(
Object.fromEntries(Object.values( // discard value as keys and convert back to map
  Object.entries(mappingParams).reduce( // merge value as keys from mappingParams
    (acc,x,k) => (acc[k=x[1].toLowerCase()] && (acc[k]=x), acc), 
    // create map of value as keys on parsedCodedParams
    Object.entries(parsedCodedParams).reduce((acc,x)=>(acc[x[1].toLowerCase()]=x,acc), {})
  )
))
);

// preserves order of parsedCodedParams
console.log(
Object.fromEntries(Object.values( // discard index i as key and convert back to map
Object.fromEntries(Object.values( // discard value as keys and convert to map with key as index i
  Object.entries(mappingParams).reduce( // merge value as keys from mappingParams (preserving index i)
    (acc,x,i,k) => (acc[k=x[1].toLowerCase()] && (acc[k][1]=x), acc), 
    // create map of value as keys on parsedCodedParams
    Object.entries(parsedCodedParams).reduce((acc,x,i)=>(acc[x[1].toLowerCase()]=[i,x],acc), {})
  )
))
))
);

Upvotes: 0

Barmar
Barmar

Reputation: 781741

You're changing the value, not the key. There's no way to replace a key directly, you have to add a new key and delete the old one.

Also, you're comparing the value with a key, not comparing the values.

let parsedCodedParams = {a: "1", b:"2", c: "3"};
let mappingParams= { d:"1", z:"5"};

for (var [key, value] of Object.entries(parsedCodedParams)) {
  for (var [k, v] of Object.entries(mappingParams)) {
    if (v.toLowerCase() == value) {
      parsedCodedParams[k] = v;
      delete parsedCodedParams[key];
    }
  }
}

console.log(parsedCodedParams)

Upvotes: 1

Related Questions