简体   繁体   English

当键为动态键时,按值对对象数组进行排序

[英]Sort an array of objects by value when the key is dynamic

I want to sort an array objects like so. 我想像这样对数组对象进行排序。

var obj = [{"UMAIR":410},
        {"ALI":2177},   
        {"JOHN":410},
        {"ANTHENY":410},
        {"FRANKLY":410},
        {"FRONTY":534},
        {"SLIM":534},
        {"ASFUND":534}];

I want to sort it with integer values of each object. 我想用每个对象的整数值对它进行排序。 I am trying to understand following code (that I have found online): 我正在尝试理解以下代码(我在网上找到):

 obj.sort(function(a, b) {
    return a.price - b.price;
});

But in this code its using price property, but I dont' have any specific property here. 但是在这段代码中,它的使用价格属性,但是我在这里没有任何特定的属性。

You can try the sort function... 您可以尝试排序功能...

obj.sort(function(a,b) {
   return a[Object.keys(a)[0]] - b[Object.keys(b)[0]];
});

is Equivalent to: 等效于:

obj.sort(function(a,b) {
   var aValue = a[Object.keys(a)[0]];
   var bValue = b[Object.keys(b)[0]];
   if (aValue > bValue)
     return 1;
   else if (aValue < bValue)
     return -1;
   else
     return 0;
}); 

Edit, Just saw your edit, yeah you did find it. 编辑,刚看到您的编辑,是的,您确实找到了。 You should also search how to extract elements from json, which in your case is Object.keys, 您还应该搜索如何从json(在您的情况下为Object.keys)提取元素,

It Returns an array with the key strings. 它返回包含键字符串的数组。

Since your Object contains a SINGLE key, you get from the array the first value (0) and then, you are making the subtraction of values from a to b. 由于您的对象包含一个SINGLE键,因此您将从数组中获得第一个值(0),然后将值从a减去到b。

a,b are entries of your array. a,b是数组的条目。 they are objects. 他们是对象。

In this Link you can check how sorting function works 在此链接中,您可以检查排序功能的工作方式

Code from the Link i provided 我提供的链接中的代码

function compare(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM