talent in making
talent in making

Reputation: 69

How to replace array of one object key with another array of object key in react

I have an object:

{Color: 'val 1', Name: 'val 2', Id: '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 from the other object.

{color: 'val 1', name: 'val 2', id: 'val 3'}

The expected output would be:

{color: 'val 1', name: 'val 2', id: 'val 3'}

Only the key of first object will change to the key of second object

Upvotes: 1

Views: 681

Answers (1)

StepUp
StepUp

Reputation: 38114

It is possible to iterate through keys to check whether it contains the same key, but in upper case:

for (let key in shouldBeRenamed) {
    if (etalon.hasOwnProperty(key.toLowerCase())) {
        newObj[key.toLowerCase()] = shouldBeRenamed[key];
    } else {
        newObj[key] = shouldBeRenamed[key];
    }
}

An example:

let shouldBeRenamed = {Color: 'val 1', Name: 'val 2', Id: 'val 3', Test: 1};
let etalon = {color: 'val 1', name: 'val 2', id: 'val 3'}

keyToLowerCase =(shouldBeRenamed, etalon) =>
{
const newObj = {};
for (let key in shouldBeRenamed) {
    if (etalon.hasOwnProperty(key.toLowerCase())) {
        newObj[key.toLowerCase()] = shouldBeRenamed[key];
    } else {
        newObj[key] = shouldBeRenamed[key];
    }
}
return newObj
}

console.log(keyToLowerCase(shouldBeRenamed, etalon))

Upvotes: 1

Related Questions