按键数排序对象数组(JavaScript) [英] Sort Array Of Objects By Number of Keys (JavaScript)

查看:80
本文介绍了按键数排序对象数组(JavaScript)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好我有一个对象数组(其中20个)我已经用这种格式在Angular项目中创建列(注意对象中有对象)。我希望按对象排序大多数键(在数组中的每个对象内),对象在数组中的对象内部使用最少的数字键,这样当它们以列显示时,它最有意义。

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 them by object with most keys (inside each object in array), to object with least number keys inside object in array) so that when they are displayed in columns it makes the most sense.

我正在改变一个导航栏变量,用于可点击的高级搜索。感谢您的帮助,因为这是我作为新开发者的第一个大项目。

I'm mutating a navbar variable to use for a clickable advanced search. Thanks for the help as this is my first big project as a new developer.

var clickableFilters = [
  {"State": {
    "0": [{value: "liquid"}, {count: 30}]
    }
  },
  {"Country": {
    "0": [{value: "USA"}, {count: 50}]
    "1": [{value: "Nigeria"}, {count: 90}]
    }
  },
  {"Color": {
    "0": [{value: "blue"}, {count: 30}]
    "1": [{value: "purple"}, {count: 50}]
    "2": [{value: "green"}, {count: 100}]
    }
  }
 ]

如何按键数(内部对象中的键)对对象进行排序,以便最终(在JavaScript中)

How do I sort the objects by number of Keys (keys in inner object) so that it ends up (in JavaScript)

 [{"Color": {}}, {"Country": {}}, {"State": {}}]


推荐答案

解决方案1



使用 Array.prototype.sort 的自定义比较器你需要它做什么

Solution 1

Using a custom comparator for Array.prototype.sort does what you need it to do

let data = [{a:1,b:2,c:3}, {a:1}, {a:1,b:2,c:3,d:4}, {a:1,b:2}]

data.sort((a,b) => Object.keys(a).length - Object.keys(b).length)

console.log(data)

如果您的数据是嵌套的,则子数据应附加到已知<的属性/ em> name

If your data is nested, the child data should be attached to a property of a known name

let data = [
  {foo: 'W', bar: {a:1,b:2,c:3}},
  {foo: 'X', bar: {a:1}},
  {foo: 'Y', bar: {a:1,b:2,c:3,d:4}},
  {foo: 'Z', bar: {a:1,b:2}}
]

let keyToSort = "bar";
data.sort((a,b) => Object.keys(a[keyToSort]).length - Object.keys(b[keyToSort]).length)

console.log(data)

另一方面,如果保证总是只有一个键(可能带有未知/动态名称),你可以写

On the other hand, if it is guaranteed to always have exactly one key (perhaps with an unknown/dynamic name), you could write

Object.keys(a[Object.keys(a)[0]]).length

然而,这显然非常难看并且容易出错(如果它是 有更多的键 - 或者根本没有键。如果您可以控制数据结构,那么您应该考虑重构它,因为只有一个键的Object没有多大意义 - 您也可以只删除一个嵌套级别。

This however is obviously very ugly and error prone (what if it does have more keys - or none at all). If you have control over the data structure, you should think about refactoring it, since an Object with only one key makes not much sense - you could as well just drop one nesting level.

你应该养成与复杂性作斗争的习惯—每当它顽固的头脑,抓住你的员工并发挥同样顽固的力量。

You should be in the habit of battling complexity — whenever it rears its stubborn head, grasp your staff and exert an equally stubborn force back upon it.

上面的第一个解决方案似乎有些可控,但第二个解决方案开始得到很厚如果您将解决方案分解为可重复使用的小部件,则可以相对轻松地保持复杂性。

The first solution above appears somewhat manageable, but the second one starts to get pretty thick. If you break your solution down into tiny reusable parts, you can keep complexity at bay with relative ease.

const ascComparator = (a,b) => a < b ? -1 : a > b ? 1 : 0

// use this if you want to sort data descending instead of ascending
const descComparator = (a,b) => ascComparator(b,a)

const prop = x => y => y[x]

const len = prop('length')

const comp = f => g => x => f (g (x))

const keylen = comp (len) (Object.keys)

let data = [
  {foo: 'W', bar: {a:1,b:2,c:3}},
  {foo: 'X', bar: {a:1}},
  {foo: 'Y', bar: {a:1,b:2,c:3,d:4}},
  {foo: 'Z', bar: {a:1,b:2}}
]

// same as solution #2 but much more descriptive
// "sort ascending using keylen of a.bar compared to keylen of b.bar"
data.sort((a,b) => ascComparator(keylen(a.bar), keylen(b.bar)))

console.log(data)

打破复杂性是投资未来的一种方式。一旦你在自己的程序中包含了一些复杂性,它将在以后随时为您服务。较小的程序也更容易测试。

Breaking complexity down is a way of investing in your future. Once you wrap a bit of complexity up in its own procedure, it will always be at your disposal at a later time. Smaller procedures are also easier to test.

以上每个程序 ascComparator prop len comp keylen 立即明显意图。您可以随时重新访问这些内容并轻松理解它们。使用它们的结果是,它使您的类型更易于读/写。

Each of the procedures above ascComparator, prop, len, comp, and keylen have immediately apparent intent. You can revisit these at any time and understand them with ease. And as a result of employing them, it makes your sort that much easier to read/write too.

这篇关于按键数排序对象数组(JavaScript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆