简体   繁体   English

按值对JavaScript对象进行排序

[英]Sort JavaScript object by value

I want rearrange the key value pair in a javascript object based on the value. 我想根据值在javascript对象中重新排列键值对。

  var in = {
      'b': 'asdsad',
      'm': [{
          '0': 'asdsad'
      }, {
          '1': 'masdas'
      }, {
          '4': 'dsfdsfsdf'
      }],
      'c': 'masdas',
      'a': [{
          'b': 'asdsad'
      }, {
          'c': 'masdas'
      }, {
          'k': 'dsfdsfsdf'
      }],
      'z': 'asdasdads'
  }

I want to rearrange the object so that I will have the arrays as the last key value pairs. 我想重新排列对象,以便将数组作为最后一个键值对。

Expected output 预期产量

var out = {
    'b': 'asdsad',
    'c': 'masdas',
    'z': 'asdasdads',
    'm': [{
        '0': 'asdsad'
    }, {
        '1': 'masdas'
    }, {
        '4': 'dsfdsfsdf'
    }],
    'a': [{
        'b': 'asdsad'
    }, {
        'c': 'masdas'
    }, {
        'k': 'dsfdsfsdf'
    }]
}

According to the JavaScript specification's definition of Object: 根据JavaScript规范对Object的定义:

It is an unordered collection of properties each of which contains a primitive value, object, or function. 它是属性的无序集合,每个属性都包含原始值,对象或函数。 A function stored in a property of an object is called a method. 存储在对象属性中的函数称为方法。

If you want to access the keys in an ordered fashion, you should use a structure that supports ordering, like an Array. 如果要以有序方式访问键,则应使用支持排序的结构,例如数组。

Hi Javascript sort based on value can only be done if there are fields with respective to it datastructure... below example sorts array with field value pls check out. 嗨,基于Java值的排序只能在存在与数据结构相对应的字段的情况下进行...下面的示例对具有字段值pls的数组进行检出。 Sort array of objects by string property value in JavaScript 在JavaScript中按字符串属性值对对象数组进行排序

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

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