简体   繁体   English

重新排列json对象中的数组

[英]Reorder arrays within json object

var data = {
 chart : 'rank',
 labels: [
      {
       0: 'First Choice'
       1: 'Second Choice',   
       2: 'Third Choice',
       3: 'Fourth Choice',
       4: 'Fifth Choice'
      }
 ],
rows: [
     {
      0: 2,
      1: 8,
      2: 1,
      3: 30
      4: 4
     }
      ]

   }

Is there a way to reorder the results so that the rows are reordered highest to lowest and the corresponding labels are reordered too like the below: 有没有一种方法可以对结果进行重新排序,以便将行从高到低重新排序,并且将相应的标签也重新排序,如下所示:

var data = {
 chart : 'rank',
 labels: [
      {
       0: 'Fourth Choice'
       1: 'Second Choice',   
       2: 'Fifth Choice',
       3: 'First Choice',
       4: 'Third Choice'
      }
 ],
rows: [
     {
      0: 30,
      1: 8,
      2: 4,
      3: 2
      4: 1
     }
      ]

   }

So far I have managed to reorder the rows array using the following but stuck when it comes to labels? 到目前为止,我已经设法使用以下命令对行数组进行重新排序,但是在标签方面却卡住了?

rows = rows.sort(function(a, b){return b-a});

Get the object values into an array and sort it. 将对象值放入数组中并进行排序。 After sorting update the real object based on sorted array. 排序后,根据排序后的数组更新实际对象。

 var data = { chart: 'rank', labels: [{ 0: 'First Choice', 1: 'Second Choice', 2: 'Third Choice', 3: 'Fourth Choice', 4: 'Fifth Choice' }], rows: [{ 0: 2, 1: 8, 2: 1, 3: 30, 4: 4 }] }; // get object property name array Object.keys(data.labels[0]) // generate array with object values .map(function(k) { return [data.labels[0][k], data.rows[0][k]] // sort the array based on rows value in array }).sort(function(a, b) { return b[1] - a[1]; // iterate and update real object }).forEach(function(v, i) { data.labels[0][i] = v[0]; data.rows[0][i] = v[1]; }); console.log(data); 

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

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