简体   繁体   中英

Sort JavaScript object by value

I want rearrange the key value pair in a javascript object based on the value.

  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:

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. Sort array of objects by string property value in JavaScript

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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