对对象进行排序,以使最大的嵌套数组排在最前面

时间:2020-04-15 06:10:12

标签: javascript lodash

此处的菜鸟Javascript问题:我有一个包含这样数组的对象

const obj = {
  'red': [ 'a', 'b', 'c'],
  'blue': [ 'a' ],
  'green': [ 'a', 'b', 'c', 'd', 'e' ]
}

我想对对象进行排序,以使具有最大数组的属性排在首位

obj = {
  'green': [ 'a', 'b', 'c', 'd', 'e' ],
  'red': [ 'a', 'b', 'c'],
  'blue': [ 'a' ]
}

有没有一种简单的单线或lodash方法可以实现?

2 个答案:

答案 0 :(得分:2)

将对象转换为数组。根据需要对数组进行排序,然后从该数组重新构建对象,如下所示:

const obj = {
  'red': ['a', 'b', 'c'],
  'blue': ['a'],
  'green': ['a', 'b', 'c', 'd', 'e']
};

const ordered = {};
const asArray = Object.keys(obj).map(key => ({
  key,
  arr: obj[key]
})); // create an array from the object


asArray.sort((a, b) => b.arr.length - a.arr.length); // sor the array so the array has bigger length should come first

asArray.forEach(r => {
  ordered[r.key] = r.arr
}); // re construct as new object
console.log(ordered);

答案 1 :(得分:1)

先排序再分配

const obj = {
  'red': [ 'a', 'b', 'c'],
  'blue': [ 'a' ],
  'green': [ 'a', 'b', 'c', 'd', 'e' ]
};

const newObj = {};

let sorted = Object.keys(obj)
    .sort((a, b) => obj[b].length - obj[a].length).forEach(e => newObj[e] = obj[e]);
    
console.log(newObj);