forループ内の値に基づいて、ネストされたJSONオブジェクトをソート?

制限:

期待して誰かがここに私を助けたり、少なくとも正しい方向に私を指すことができます。私はこれがソート取得しようと時間を費やしていると私は失われています。

以下のコードは、私の実際のJSONはjqueryのを使用してAJAXを介して返され、ただのモックです。私の問題は、ソートが、ネストされたJSONオブジェクトにソートされていません。

私は、コストに基づいたJSON出力をソートしようとしています。(最高から最低のコスト)は、私の試みは失敗していると私は、このソートを取得することはできません。私は、「並べ替え」定義されていない得続けます。

任意の助けいただければ幸いか、あなただけの私がここで間違ってやっているものを指摘することができます。

var json = '{"shipping_method":{"ups":{"title":"United Parcel Service","quote":{"12":{"code":"ups.12","title":"UPS 3 Day Select","cost":117.3,"tax_class_id":"0","text":"$117.30"},"13":{"code":"ups.13","title":"UPS Next Day Air Saver","cost":242.52,"tax_class_id":"0","text":"$242.52"},"14":{"code":"ups.14","title":"UPS Next Day Air Early A.M.","cost":279.95,"tax_class_id":"0","text":"$279.95"},"03":{"code":"ups.03","title":"UPS Ground","cost":54.62,"tax_class_id":"0","text":"$54.62"},"02":{"code":"ups.02","title":"UPS 2nd Day Air","cost":177.31,"tax_class_id":"0","text":"$177.31"},"01":{"code":"ups.01","title":"UPS Next Day Air","cost":248.08,"tax_class_id":"0","text":"$248.08"}},"sort_order":"","error":""}}}';

    /* 

    This doesnt work and returns undefined. 
    
    json["shipping_method"]["quote"].sort(function(a, b) {
        return a['cost'] > b['cost'];
      });

    // I found this example, but also didn't work.
    custSort = (prop1, prop2 = null, direction = 'asc') => (e1, e2) => {
    const a = prop2 ? e1[prop1][prop2] : e1[prop1],
    b = prop2 ? e2[prop1][prop2] : e2[prop1],
    sortOrder = direction === "asc" ? 1 : -1
     return (a < b) ? -sortOrder : (a > b) ? //sortOrder : 0;
    };      

   json.sort(custSort("quote", "cost", "desc"));*/


json = JSON.parse(json);

for (var i in json["shipping_method"]) {

  // EDIT::  I want the sorting to occur here if possible. 

  for (j in json["shipping_method"][i]["quote"]) {


  //EDIT::  I want to keep this for loop, but with the results sorted by cost 

    console.log(json["shipping_method"][i]["quote"][j]["cost"]);

  }

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

マイク:

ソート配列に変換オブジェクト

あなたは(メソッドと引用符を出荷など)のメタデータの一部を参照することができるように下に行われたように、あなたのオブジェクトを平らにしたいかもしれません。その後、配列にそれを保存し、試みたとして、それを並べ替えることができます。

const json = JSON.parse(getData());

for (let method in json["shipping_method"]) {
  // cache
  let quotes = json['shipping_method'][method]['quote']
  
  // convert object to array and sort
  let sortedQuotes = Object.values(quotes).sort((a, b)=>a.cost-b.cost);
  
  console.log(sortedQuotes)
}


/* Dummy Data */
function getData() {
  return '{"shipping_method":{"ups":{"title":"United Parcel Service","quote":{"12":{"code":"ups.12","title":"UPS 3 Day Select","cost":117.3,"tax_class_id":"0","text":"$117.30"},"13":{"code":"ups.13","title":"UPS Next Day Air Saver","cost":242.52,"tax_class_id":"0","text":"$242.52"},"14":{"code":"ups.14","title":"UPS Next Day Air Early A.M.","cost":279.95,"tax_class_id":"0","text":"$279.95"},"03":{"code":"ups.03","title":"UPS Ground","cost":54.62,"tax_class_id":"0","text":"$54.62"},"02":{"code":"ups.02","title":"UPS 2nd Day Air","cost":177.31,"tax_class_id":"0","text":"$177.31"},"01":{"code":"ups.01","title":"UPS Next Day Air","cost":248.08,"tax_class_id":"0","text":"$248.08"}},"sort_order":"","error":""}}}';
}
.as-console-wrapper {
  max-height: 100vh !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

配送方法ごとのコストによって引用符

これは、(おそらく、行に配置されるように)引用IDが必要であることを前提とし、そうでない場合は、これは使用して簡素化することができるObject.valuesの代わりにObject.entries(他の変化の中で)。

何無視output機能がやっています。これは、適切なセル順序を保証するものではないことを、簡単な例であり、他の制約と脆弱性のホストを持っています。唯一のオリジナルことを実証するために使用されるquoteデータは、ソート後も使用可能です。

const data = JSON.parse(getData());

for (let method in data.shipping_method) {
  output({row: method}, {class:'capitalize'})
  
  // cache
  let quotes = data.shipping_method[method].quote
  let sortContent = Object.entries(quotes);
  let sortedQuotes = sortContent.sort((a,b)=>a[1].cost-b[1].cost).map(i=>i[0]);
  
  for (let quoteId of sortedQuotes){
    let quoteInfo = quotes[quoteId];
    output({cell: quoteInfo})
  }
}

/* Dummy Data */
function getData() {
  return '{"shipping_method":{"ups":{"title":"United Parcel Service","quote":{"12":{"code":"ups.12","title":"UPS 3 Day Select","cost":117.3,"tax_class_id":"0","text":"$117.30"},"13":{"code":"ups.13","title":"UPS Next Day Air Saver","cost":242.52,"tax_class_id":"0","text":"$242.52"},"14":{"code":"ups.14","title":"UPS Next Day Air Early A.M.","cost":279.95,"tax_class_id":"0","text":"$279.95"},"03":{"code":"ups.03","title":"UPS Ground","cost":54.62,"tax_class_id":"0","text":"$54.62"},"02":{"code":"ups.02","title":"UPS 2nd Day Air","cost":177.31,"tax_class_id":"0","text":"$177.31"},"01":{"code":"ups.01","title":"UPS Next Day Air","cost":248.08,"tax_class_id":"0","text":"$248.08"}},"sort_order":"","error":""}}}';
}

/* Really simple output for demo purpose */
function output(data, options={}){

  if ('row' in data){
    let $col = $('<td></td>', options).html(data.row)
    let $row = $('<tr></tr>').append($col);
    $('tbody').append( $row )
  }
  
  else if ('cell' in data){
    let $row = $('<tr></tr>')
    for( let key in data.cell ){
      let $col = $('<td></td>', options).html(data.cell[key])
      $row.append($col)
    }
    $('tbody').append( $row )
  }
  
}
.capitalize {
  text-transform: uppercase;
}

td {
  min-width: 5rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
  <thead></thead>
  <tbody></tbody>
</table>

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=32458&siteId=1