JavaScript按属性值排序字典

时间:2016-01-11 21:05:23

标签: javascript arrays node.js sorting dictionary

我在JavaScript中有一个字典样式的数组对象,如下所示,并希望按属性对其进行排序。怎么做?我知道类似的问题已得到解答,但我认为我的结构不同。简单地运行array.sort(compare)对我来说不起作用,因为我没有索引的整数。谢谢!

var myData = {
    "userOne": {
        "firstName": "Felix",

    },
    "userTwo": {
        "firstName": "Bob",

    },
    "userThree": {
        "firstName": "Anna",

    }
}

我希望上面的数组myDatafirstName排序,以便首先显示Anna的对象,然后显示Bob,然后显示Felix }。非常感谢你!!

3 个答案:

答案 0 :(得分:5)

您可以使用可迭代的ES6地图:

class FragOne extends ListFragment
      {     
      ListenerInterface listener;

            ...
       public void OnListItemClick(ListView, View,position,id)
            {
             listener.doSmth(someData);
            }

       public void assignListener(Activity activity)
              {
                this.listener=(ListenerInterface)activity;

              }
       public interface ListenerInterface
            {
               public void doSmth(someData);
            }

      }
class MainActivity extends Activity implements FragOne.ListInterface
{
    ....
    public void onCreate(Bundle s)
          }
            FragOne fragOne = new FragOne();
            FragmentManager fm=getSupportFragmentmentManager...       
             ...
             ...commit();
            fragOne.assignListener(this);
          }

   public void doSmth(someData)
    {
       //sending data to second fragment
    }
}

答案 1 :(得分:2)

不幸的是,您的数据格式无法实现。我们在这里处理JS对象。根据定义:

  

对象是Object类型的成员。 它是一个无序的属性集合,每个属性都包含一个原始值,对象或函数。存储在对象属性中的函数称为方法。

如果你把它作为对象数组,那可能会有所帮助。

答案 2 :(得分:2)

这里有一些代码可以解决你的底层问题,通过创建一个数组而不是一个对象,填充了基于键排序的内部对象:

arrayOfSortedObjects = Object.keys(myData).sort(function(a,b) {
    return myData[a].firstName.localeCompare(myData[b].firstName);
}).map(function(k) {
    return myData[k];
});
相关问题