Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to case-insensitively set value in object in Javascript?

Tags:

javascript

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.

like image 550
user944513 Avatar asked Nov 05 '18 14:11

user944513


1 Answers

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);
like image 148
Thatkookooguy Avatar answered Sep 28 '22 20:09

Thatkookooguy