对嵌套对象的javascript数组进行排序

时间:2016-03-15 19:59:49

标签: javascript jquery arrays sorting object

我是JavaScript的新手,我尽可能多地学习,但觉得我已经碰到了我想要做的事情。

我的问题是,我在每个对象中有一个对象数组是一个shop对象,这是一个“类型”修复对象,具有修复成本的属性。

我如何按价格对此进行排序?到目前为止,请查看我的代码。我需要按价格顺序退回商店对象,因为我仍然需要商店的所有信息,但是根据所做的选择按修理价格的顺序,所以基本上按照选择顺序返回数组中的商店对象。可能不可能我不知道,任何想法将不胜感激。我提前感谢你的时间。

var vendors = [

  {
    mosShop: {
      samsung: {
        screen: 50,
        button: 10,
        back: 20
      },
      iphone: {
        screen: 10,
        button: 18,
        back: 1
      }
    }
  }, {
    davesShop: {
      samsung: {
        screen: 40,
        button: 5,
        back: 12
      },
      iphone: {
        screen: 18,
        button: 148,
        back: 11
      }

    }
  }


];
var arr = [];
//;
$('#phone,#repair').change(function() {



  var selectedPhone = $('#phone :selected').text().toString();
  var selectRepair = $('#repair :selected').text().toString();




  for (var i = 0; i < vendors.length; i++) {

    var mo = Object.keys(vendors[i]);
    var t = mo.toString()

    var price = vendors[i][t][selectedPhone][selectRepair];

    alert(price)


  }













});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<select id="phone">
  <option value="samsung">samsung</option>
  <option value="iphone">iphone</option>
  <option value="mercedes">blah</option>
  <option value="audi">blah</option>
</select>
<select id="repair">
  <option value="screen">screen</option>
  <option value="button">button</option>
  <option value="back">back</option>
  <option value="audi">blah</option>
</select>

<div id="endresults">

</div>

`

1 个答案:

答案 0 :(得分:4)

要根据selectedPhoneselectRepair的值对数组进行排序,您可以像这样使用本机sort()函数 -

function shopPrices(selectedPhone, selectedRepair) {
    return vendors.sort(function(a,b) { 
        var shopA = Object.keys(a)[0];
        var shopB = Object.keys(b)[0];
        return (a[shopA][selectedPhone][selectedRepair] - b[shopB][selectedPhone][selectedRepair]);
    });
} 

然后您可以通过传递selectedPhoneselectedRepair值来调用该函数,如下所示 -

var sorted = shopPrices('samsung','screen');
//Result -> [{"davesShop":{"samsung":{"screen":40,"button":5,"back":12},"iphone":{"screen":18,"button":148,"back":11}}},{"mosShop":{"samsung":{"screen":50,"button":10,"back":20},"iphone":{"screen":10,"button":18,"back":1}}}]

var anotherTest = shopPrices('iphone','screen');
//Result -> [{"mosShop":{"samsung":{"screen":50,"button":10,"back":20},"iphone":{"screen":10,"button":18,"back":1}}},{"davesShop":{"samsung":{"screen":40,"button":5,"back":12},"iphone":{"screen":18,"button":148,"back":11}}}]

希望这有帮助!