所以我有一个看起来像这样的JSON数组:

[
  {
    row: [
      {
        boat: {
          description: 'Books',
          version: '2',
          id: 6
        },
        airplanes: [
          {
            airplane: [
              {
                description: 'DVD',
                version: 2,
                uid: 69,
                wid: 65,
                id: 84
              }
            ],
            trains: {
              train: [
                {
                  description: 'Pictures',
                  version: 2,
                  id: 149
                }
              ],
              actions: [
                {
                  description: 'This is a really long sentence.',
                  version: 2,
                  tid: 69.01,
                  id: 452
                },
                {
                  description: 'article 2',
                  version: 2,
                  tid: 69.02,
                  id: 453
                },
                {
                  description: 'developer 1',
                  version: 2,
                  tid: 69.03,
                  id: 454
                }
              ]
            }
          },
          {
            airplane: [
              {
                description: 'Games',
                version: 2,
                uid: 65,
                wid: 61,
                id: 80
              }
            ],
            trains: {
              train: [
                {
                  description: 'another great descriptions.',
                  version: 2,
                  id: 145
                }
              ],
              actions: [
                {
                  description: 'being indecisive is good.',
                  version: 2,
                  tid: 65.01,
                  id: 442
                },
                {
                  description: 'couches are comfortable',
                  version: 2,
                  tid: 65.02,
                  id: 443
                }
              ]
            }
          }
        ]
      }
    ]
  }
]


我试图按“ wid”的升序对上述输出进行排序,但仍然能够保留整体顺序。例如,在上面的示例中,数组元素0中的wid为65,而数组元素1中的wid值为61。因此,应该交换元素1和元素0。有没有内置的javascript方法可以像这样对json进行排序?

我将得到一个比提供的示例大得多的json数组输出。

最佳答案

Underscore和LoDash都有一种可以满足您需要的排序方法。在此示例中,我假设您显示的数据结构存储在名为data的变量中。

 _.each(data, function(obj) {
     _.each(obj.row, function(row) {
        // note the reassignment, _.sortBy does not sort in-place
        row.airplanes = _.sortBy(row.airplanes, function(airplane) {
           return airplane.wid; // This will sort ascending.
                                // To sort descending, simply multiply by -1
        });
     });
 });


那这是做什么的?它采用根数据结构中的每个数组元素并对其进行循环(这是第一个_.each)。然后,在每个这些对象中,它循环遍历每个row元素,并根据每个对象中包含的row.airplanes元素对wid数组进行排序。

希望这对您有帮助。顺便说一句,您发布的数据严格来说是无效的JSON。每个键都应该用双引号引起来,即"row",而不是仅仅用row,并且单引号对于定界字符串(即用"DVD"代替'DVD')是无效的。同样,您的boat版本是字符串,而其他版本标识符是整数,最好将版本标识符保持为整数。

10-05 21:02
查看更多