Sort Array Of Objects By Number of Keys (JavaScript)

前端 未结 3 807
春和景丽
春和景丽 2021-01-16 19:36

Hi all I have an array of objects (20 of them) that I\'ve placed in this format to make columns in an Angular Project (note there are objects in objects). I want to sort the

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-16 20:03

    For your data structure you can use sort() like this.

    var arrayOfObjects = [
      {"least#OfKeysObject": {
        key1: 'value',
        }
      },
      {"secondMost#OfKeysObj": {
        key1: 'value',
        key2: 'value'
        }
      },
      {"most#OfKeysObj": {
        key1: 'value',
        key2: 'value',
        key3: 'value'
        }
      }
     ];
     
     var result = arrayOfObjects.sort(function(a, b) {
       return Object.keys(b[Object.keys(b)[0]]).length - Object.keys(a[Object.keys(a)[0]]).length;
     });
     
     console.log(result)

提交回复
热议问题