What's the best way (most efficient) to turn all the keys of an object to lower case?

前端 未结 20 2534
野性不改
野性不改 2020-12-04 20:42

I\'ve come up with

function keysToLowerCase (obj) {
  var keys = Object.keys(obj);
  var n = keys.length;
  while (n--) {
    var key = keys[n]; // \"cache\"         


        
20条回答
  •  爱一瞬间的悲伤
    2020-12-04 21:42

    Using Object.fromEntries (ES10)

    Native and immutable solution using the new Object.fromEntries method:

    
    const newObj = Object.fromEntries(
      Object.entries(obj).map(([k, v]) => [k.toLowerCase(), v])
    );
    

    Until that function becomes widely available you could define it yourself with the following polyfill:

    Object.fromEntries = arr => Object.assign({}, ...Array.from(arr, ([k, v]) => ({[k]: v}) ));
    

    A nice thing is that this method does the opposite of Object.entries, so now you can go back and forth between the object and array representation.

提交回复
热议问题