1

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

I can change a single object but what if it's an array of object
@AbhishekRoy just use this function in map function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.