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

Viewed 202

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.

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

I would normalize all the keys to follow the same pattern firstly (all keys to be lowercase), and later work with the normalized data:

const data = {
 'Key': 1,
 'test': 2,
 'Perm city': 3
}

// Normalize the data keys
Object.keys(data)
  .forEach(key => {
    // Normalize the key
    data[key.toLowerCase()] = data[key]
    
    // Delete the denormalized key with its value
    delete data[key]
  })

console.log(data['perm city'], data)

You could find the relevant key amongst all object keys

let relevantKey = Object.keys( a ).find( key => {
    let s = 'PERM CITY'
    return (key.toLowerCase( ) === s.toLowerCase( ) )
})

Object.keys method returns the keys of a Object, then find the key you need by doing a case insensitive search. Use the found key to assign to original Object.

let obj = { "X": 1 };
let key_to_find = "x";
key = Object.keys(obj).find(function(element) {
  return element.toLowerCase() == key_to_find;
});
obj[key||key_to_find] = "new value";

you can try by using a function to set a value for your obj :

 var a = {
    'perm city' :{
     value:'asda'
    }
 }


    function changeValue(obj,prop,value) {
        let propUp = prop.toUpperCase();
        let propDown = prop.toLowerCase();
        if (obj.hasOwnProperty(propUp)) {
          obj[propUp] = value;
        }
        else if (obj.hasOwnProperty(propDown)) {
                obj[propDown] = value;
        }
        else {
                console.log("No prop found in low or Uppercase")
        }
        console.log(obj);
    }
    changeValue(a,"PERM CITY","NEW");

The new obj will be :

{
        'perm city' :{
         value:'NEW'
        }
     }

function assignKeyValueCaseInsensitively(type, key, value) {
  if ((type != null) && (typeof key === 'string')) {

    var isKeyRespondsInitially = false;
    var regXKey = RegExp(key, 'i');

    Object.keys(type).forEach(function (key) {
      if (regXKey.test(key)) {
        isKeyRespondsInitially = true;

        type[key] = value;
      }
    });
    if (!isKeyRespondsInitially) {

      type[key] = value;
    }
  }
  return type;
}

var a = {
  'perm city' : 'foo',
  'PERM CITY' : 'bar',
  'Perm City' : 'baz',
  'permCity' : 'biz'
};
var b = {
  'permCity' : 'biz'
}

assignKeyValueCaseInsensitively(a, 'pERM citY', 'boz');
assignKeyValueCaseInsensitively(b, 'pERM citY', 'boz');

console.log('a : ', a);
console.log('b : ', b);
.as-console-wrapper { max-height: 100%!important; top: 0; }

Related