How to set value in object in Javascript when you don't know the key pattern?
Example:
Key value is same , but some time it is in CAPITAL or some time it is in lowercase or sometime the first letter is in uppercase and other lowercase.
var a = {
'perm city' :{
value:'asda'
}
}
if((a['perm city'] && a['perm city'].value) || (a['Perm City'] && a['Perm City'].value) || (a['PERM CITY'] && a['PERM CITY'].value)){
a['PERM CITY'] = 'DADASDASD'
}
In my example, I want to set perm city
value but I don't know which pattern it will come out.
you need to search for the key by comparing it to a lowercase version of it.
If no key was found, set the key to a default lowercase value: perm city
const data = {
'perm city': {
value: 'asda'
}
};
console.log(data);
const defaultKey = 'perm city';
const keys = Object.keys(data);
let foundKey = keys.find((key) => key.toLowerCase() === defaultKey);
foundKey = foundKey || defaultKey;
data[foundKey] = 'PIZZA';
console.log(data);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With