Javascript 比较数组中的对象

Javascript 比较数组中的对象,javascript,jquery,arrays,Javascript,Jquery,Arrays,好的,我正在制作一个产品分类表,这就是我目前所拥有的 jQuery(document).ready(function() { // starter jQuery file /* Watches Array */ var watchesArray = [ { model: "Swim", image:"", price: 149.99, sports:["Swimming"],

好的,我正在制作一个产品分类表,这就是我目前所拥有的

jQuery(document).ready(function() {
// starter jQuery file


 /* Watches Array */
    var watchesArray = [
        {
          model: "Swim", 
          image:"",
          price: 149.99,
          sports:["Swimming"],
          touchScreen:false,
          GPS:false,
          heartRateMonitor:false,
          hrZoneTraining:false,
          caloriesBurned:true,
          distance:true,
          pace:true,
          multisport:false,
          swimMetrics:true,
          memory:"Up to 30 workouts",
          virtualPartner:false,
          virtualRacer:false,
          paceAlert:false,
          timeDistanceAlert:false,
          hydrationAlert:false,
          rechargeableBattery:false,
          waterResistant:"Up to 50 meters",
          syncWithComputer:true,
          other:"",
        },
        {
          model: "FR 10", 
          image:"fr_10.jpg",
          price: 129.99,
          sports:["Running"],
          touchScreen:false,
          GPS:true,
          heartRateMonitor:false,
          hrZoneTraining:false,
          caloriesBurned:false,
          distance:true,
          pace:true,
          multisport:false,
          swimMetrics:false,
          memory:"Up to 7 workouts",
          virtualPartner:false,
          virtualRacer:false,
          paceAlert:false,
          timeDistanceAlert:false,
          hydrationAlert:false,
          rechargeableBattery:true,
          waterResistant:"Up to 50 meters",
          syncWithComputer:false,
          other:"-Virtual Pacer(compares running pace to target)</br>-Walk/Run feature",
          checkBox:"<input type='checkbox' name='he' value='jk' id='compare'>"

        },
        {
          model: "FR 15", 
          image:"fr_15.jpg",
          price: 199.99,
          sports:["Running"],
          touchScreen:false,
          GPS:true,
          heartRateMonitor:true,
          hrZoneTraining:true,
          caloriesBurned:true,
          distance:true,
          pace:true,
          multisport:false,
          swimMetrics:false,
          memory:"Up to 7 workouts",
          virtualPartner:false,
          virtualRacer:false,
          paceAlert:false,
          timeDistanceAlert:false,
          hydrationAlert:false,
          rechargeableBattery:true,
          waterResistant:"Up to 50 meters",
          syncWithComputer:false,
          other:"-Virtual Pacer (compares running pace to target) </br>Walk/Run  feature</br>-Activity",
        },
        {
          model: "FR 220", 
          image:"fr_220.jpg",
          price: 299.99,
          sports:["Running"],
          touchScreen:false,
          GPS:true,
          heartRateMonitor:true,
          hrZoneTraining:true,
          caloriesBurned:true,
          distance:true,
          pace:true,
          multisport:false,
          swimMetrics:false,
          memory:"200 hours of data",
          virtualPartner:false,
          virtualRacer:false,
          paceAlert:true,
          timeDistanceAlert:false,
          hydrationAlert:true,
          rechargeableBattery:true,
          waterResistant:"Up to 50 meters",
          syncWithComputer:true,
          other:"-Walk/Run feature</br>-Interval Training",
        },
        {
          model: "FR 620", 
          image:"fr_620.jpg",
          price: 449.99,
          sports:["Running"],
          touchScreen:true,
          GPS:true,
          heartRateMonitor:true,
          hrZoneTraining:true,
          caloriesBurned:true,
          distance:true,
          pace:true,
          multisport:false,
          swimMetrics:false,
          memory:"200 hours of data",
          virtualPartner:true,
          virtualRacer:false,
          paceAlert:true,
          timeDistanceAlert:true,
          hydrationAlert:true,
          rechargeableBattery:true,
          waterResistant:"Up to 50 meters",
          syncWithComputer:true,
          other:"-VO2 Max</div></br>-Walk/Run feature</br>-Interval Training",
        },
        {
          model: "FR 310 XT", 
          image:"",
          price: 349.99,
          sports:["Multisport"],
          touchScreen:false,
          GPS:true,
          heartRateMonitor:true,
          hrZoneTraining:true,
          caloriesBurned:true,
          distance:true,
          pace:true,
          multisport:true,
          swimMetrics:false,
          memory:"1000 laps",
          virtualPartner:true,
          virtualRacer:true,
          paceAlert:true,
          timeDistanceAlert:true,
          hydrationAlert:true,
          rechargeableBattery:true,
          waterResistant:"Up to 50 meters",
          syncWithComputer:true,
          other:"-Interval Training",
        },
        {
          model: "FR70", 
          image:"",
          price: 149.99,
          sports:["Fitness"],
          touchScreen:false,
          GPS:false,
          heartRateMonitor:true,
          hrZoneTraining:true,
          caloriesBurned:true,
          distance:true,
          pace:true,
          multisport:false,
          swimMetrics:false,
          memory:"Up to 20 hrs of data",
          virtualPartner:true,
          virtualRacer:false,
          paceAlert:true,
          timeDistanceAlert:true,
          hydrationAlert:false,
          rechargeableBattery:false,
          waterResistant:"Up to 50 meters",
          syncWithComputer:true,
          other:"-Interval Training",
        },
    ];

/* End Watch Array */

/* different sports arrays filtered */

var runningArray = watchesArray.filter(function(watch) {
            return watch.sports.indexOf('Running') !== -1;
        });
var swimmingArray = watchesArray.filter(function(watch) {
            return watch.sports.indexOf('Swimming') !== -1;
        });
var multisportArray = watchesArray.filter(function(watch) {
            return watch.sports.indexOf('Multisport') !== -1;
        });
var fitnessArray = watchesArray.filter(function(watch) {
            return watch.sports.indexOf('Fitness') !== -1;
        });

function compare() {
    if ($('#page-2 div:nth-of-type(1)').hasClass('running-category')) {
        var sportArray = runningArray;
    }
    if ($('#page-2 div:nth-of-type(2)').hasClass('swimming-category')) {
        var sportArray = swimmingArray;
    }
    if ($('#page-2 div:nth-of-type(3)').hasClass('multisport-category')) {
        var sportArray = multisportArray;
    }
    if ($('#page-2 div:nth-of-type(4)').hasClass('fitness-category')) {
        var sportArray = fitnessArray;
    }


    var sportArrayLength = $(sportArray).length;

    for (var i = 0; i < sportArrayLength; i++) {
        var watchModel = "<div class='watch-model'>"+sportArray[i].model+"</div>",
        watchImage = "<div class='watch-image'>"+sportArray[i].image+"</div>",
        watchPrice = "<div class='watch-price'>$"+sportArray[i].price+"</div>",
        watchSports = "<div class='watch-sports'>"+sportArray[i].sports+"</div>",
        watchTouch = "<div class='watch-touch'>"+sportArray[i].touchScreen+"</div>",
        watchGPS = "<div class='watch-gps'>"+sportArray[i].GPS+"</div>",
        watchHeart = "<div class='watch-heart'>"+sportArray[i].heartRateMonitor+"</div>",
        watchHRZone = "<div class='watch-zone'>"+sportArray[i].hrZoneTraining+"</div>",
        watchCalories = "<div class='watch-calories'>"+sportArray[i].caloriesBurned+"</div>",
        watchDistance = "<div class='watch-distance'>"+sportArray[i].distance+"</div>",
        watchPace = "<div class='watch-pace'>"+sportArray[i].pace+"</div>",
        watchMultiSport = "<div class='watch-swim-metrics'>"+sportArray[i].multisport+"</div>",
        watchSwimMetrics = "<div class='watch-multi'>"+sportArray[i].multisport+"</div>",
        watchMemory = "<div class='watch-memory'>"+sportArray[i].memory+"</div>",
        watchVirtualPartner = "<div class='watch-virtual-partner'>"+sportArray[i].virtualPartner+"</div>",
        watchVirtualRacer = "<div class='watch-virtual-racer'>"+sportArray[i].virtualRacer+"</div>",
        watchPaceAlert = "<div class='watch-pace-alert'>"+sportArray[i].paceAlert+"</div>",
        watchTimeDistanceAlert = "<div class='watch-time-distance-alert'>"+sportArray[i].timeDistanceAlert+"</div>",
        watchHydrationAlert = "<div class='watch-hydration'>"+sportArray[i].hydrationAlert+"</div>",
        watchRechargeable = "<div class='watch-rechargeable'>"+sportArray[i].rechargeableBattery+"</div>",
        watchWaterResistance = "<div class='watch-water-resistance'>"+sportArray[i].waterResistant+"</div>",
        watchSync = "<div class='watch-syncs'>"+sportArray[i].syncWithComputer+"</div>",
        watchOther = "<div class='watch-other'>"+sportArray[i].other+"</div>",
        watchesTotal ="<div class='item-container'>"+ watchModel + watchImage + watchPrice + watchSports + watchTouch + watchGPS + watchHeart + watchHRZone + watchCalories + watchDistance + watchPace + watchMultiSport + watchSwimMetrics + watchMemory + watchVirtualPartner + watchVirtualRacer + watchPaceAlert + watchTimeDistanceAlert + watchHydrationAlert + watchRechargeable + watchWaterResistance + watchSync + watchOther+"</div>" 
         ;

         $('.comparison-container').append(watchesTotal);
        // alert(watchModel)
    }

} //end function

$("#page-4 .continue-button").click(function() {
  $('.comparison-container').empty();
    compare();
 });




   //var inArray = $.inArray(true, watchesArray[0].multisport)
  // alert(inArray)




}); // ready method
因此,流程基本上是单击一项运动,在数组中进行筛选,并仅使用具有该运动的项目创建新数组,然后选择要具有的som功能,然后单击“继续”时,将显示符合条件的项目

最后一个问题是,当显示这些手表时,我必须能够选中我感兴趣的产品的复选框,这样我才能继续,并让所选手表显示其所有详细信息。所以基本上我需要找出如何通过从页面中选择我想要的对象来比较数组中的两个对象

在第3页,你们基本上有一个数组项的列表,每个项目下都有一个比较复选框。我只需要能够将选择的产品传递到下一页

如何比较阵列中的两个对象

使用JSON.stringify比较文本:

var foo = [{"1":2},{"1":3},{"2":3},{"1":2}];
var bar = JSON.stringify(foo[0]) === JSON.stringify(foo[1]);
var baz = JSON.stringify(foo[0]) === JSON.stringify(foo[3]);
使用数组作为第二个参数以保证键枚举的顺序:

(JSON.stringify({a: 1, b: 2}, ["a","b"]) === JSON.stringify({b: 2, a: 1}, ["a","b"]))

增加代码可读性的建议有助于调试并帮助人们理解您的代码:您可以使用多个类并将多个类赋予以下对象:$'page-3,page-4,page-5'。removeClass'running-background fitness background Multiport background Swinging background';你能把你的代码简化成与问题相关的部分吗?所有removeClass内容都重要吗?发布一些HTML也会有帮助。@DavidKnipe您可以删除、修复或忽略它。JSON.stringify{a:1,b:2}==JSON.stringify{a:1,b:2}在我测试过的所有地方都是正确的,上面发布的场景不是问题的一部分。我不能删除它,因为它不是我的答案,我不能修复它,因为它有根本性的缺陷,最好警告人们错误的答案,而不是忽略它们。为了清晰起见,soktinpk给出了一个简单的例子,但同样的原则也适用于问题中的数据。即使OP记得从未定义过具有不同顺序键的对象,输出顺序也可能取决于模糊因素,例如它是否太忙,无法进行非必要的内存管理,无法在哈希表中重新分配内存。无论如何,您没有在任何地方进行测试,js规范也不能保证排序。@DavidKnipe使用第二个参数的数组强制执行顺序,如ES5-15.12.3:4.b.2所示,因此JSON.stringify{a:1,b:2}[a,b]==JSON.stringify{b:2,a:1}[a,b]按预期工作。当前已关闭,但和可供参考。我不知道。它似乎起作用了。但是对于像原始问题这样的数据来说,它比你的例子要难处理得多。您需要一个数组['model'、'image'、…、'other']来将参数字符串化。您必须确保它包括对象中的所有关键点,以及子对象中的关键点;否则,它将静默地忽略未列出的键,可能为两个非同构对象输出相同的JSON字符串。例如,他们可以通过克隆对象并添加color:black而不向数组添加颜色来添加其中一只手表的黑色版本。@DavidKnipe在更复杂的情况下,第二个参数也可以是返回数组的函数调用。