【问题标题】:iterate over json object duplicates in handlebars遍历把手中的 json 对象重复项
【发布时间】:2014-07-07 00:31:55
【问题描述】:

我的 javascript 中有以下 JSON 对象:

var source = $("#template").html();
var template = Handlebars.compile(source);

var igListOrig = [
  {
    "IG":"Problem Solving", 
    "AIR_Indicators": "All Domain 1 Indicators* 3.1, 3.2, 3.3,     3.4", 
    "SMP": "SMP 1, 2, 3, 4, 5, 6, 7, and 8", 
    "Purpose": "Students must be able to reason, problem solve, communicate and make real life       decisions that require mathematical thinking.  Teaching students problem solving skills and giving them opportunities to apply their skills is critical to developing their capacity to solve mathematical problems that arise in all our lives (e.g. starting a small business, figuring out the area of a room in order to purchase the correct amount of paint, filling out a tax return, tracking and setting goals for investments, etc.)", 
    "IP":"Problem of the Week(PoW)", 
    "What": "PoWs are complex problems.",
    "When": "PoWs should be administered once per month.", 
    "How": "1.Introduce problem, process, and rubric. 2.Students are given time in class to work on problem throughout the week. 3.Students complete write up. 4.Student peer edit write up. 5.Students revise write up"
  },

  {
    "IG":"Problem Solving", 
    "AIR_Indicators": "All Domain 1 Indicators* 3.1, 3.2, 3.3, 3.4",   
    "SMP": "SMP 1, 2, 3, 4, 5, 6, 7, and 8",
    "Purpose": "Students must be able to reason, problem solve, communicate and make real life       decisions that require mathematical thinking.  Teaching students problem solving skills and giving them opportunities to apply their skills is critical to developing their capacity to solve mathematical problems that arise in all our lives (e.g. starting a small business, figuring out the area of a room in order to purchase the correct amount of paint, filling out a tax return, tracking and setting goals for investments, etc.)",
    "IP":"Problem of the Month (POM)", 
    "What": "The POMs are divided into five levels. Students are asked to explain their solutions and reasoning in a write up.",
    "When": "Students should work on problem the first 10-15 minutes of a period for 5-7 consecutive days. ",
    "How": "Write them on a pieces of paper." 
  },

  {
    "IG":"Problem Solving", 
    "AIR_Indicators": "All Domain 1 Indicators* 3.1, 3.2, 3.3, 3.4",
    "SMP": "SMP 1, 2, 3, 4, 5, 6, 7, and 8", 
    "Purpose": "Students must be able to reason, problem solve, communicate and make real life       decisions that require mathematical thinking.  Teaching students problem solving skills and giving them opportunities to apply their skills is critical to developing their capacity to solve mathematical problems that arise in all our lives (e.g. starting a small business, figuring out the area of a room in order to purchase the correct amount of paint, filling out a tax return, tracking and setting goals for investments, etc.)", 
    "IP":"Formative Assessment Lesson (FAL)", 
    "What": "FALs consist of 3 parts including a pre-assessment (approximately 15 min.",
    "When": "The 3 part cycle is intended to be given approximately two-thirds the way into a unit of study.", 
    "How": "1.Pre assessment. 2.Introduce activity. 3.Students work collaboratively. 4.Whole class discussion/ presentation. 5.Post assessment." 
  },

 {
    "IG":"Problem Solving", "AIR_Indicators": "All Domain 1 Indicators* 3.1, 3.2, 3.3, 3.4",
    "SMP": "SMP 1, 2, 3, 4, 5, 6, 7, and 8", 
    "Purpose": "Students must be able to reason, problem solve, communicate and make real life       decisions that require mathematical thinking.  Teaching students problem solving skills and giving them opportunities to apply their skills is critical to developing their capacity to solve mathematical problems that arise in all our lives (e.g. starting a small business, figuring out the area of a room in order to purchase the correct amount of paint, filling out a tax return, tracking and setting goals for investments, etc.)",   
    "IP":"Mathematics Assessment Resources (MARS)", 
    "What": "Story Problems.",
    "When": "Done at the begining of the unit.", 
    "How": "After each asssessment." }

]

$('body').append(template(igListOrig));

我想迭代这个对象,所以只有当它迭代第二个、第三个和第四个对象时,我每次都会得到不同的“IP”、“什么”、“时间”和“如何”,并忽略所有重复。在每次迭代之后,只有“IP”、“What”、“When”和“How”不同。我需要保留这些差异并忽略其他其他重复项。

我引用了类似的东西,但我认为这个人的情况有点不同。 Iterating over a JSON-Object

最终这会出现在这样的车把模板中

<script id="template" type="text/x-handlebars-template">
<div class="container">
 {{#each this }}
    <div class='titles'>
      <div class="left">Aspire Logo</div>
      <div class="middle">{{IG}}</div>
      <div class="right">Common Core</div>
      <div class="purple"></div>
    </div>
    <div class="split">
      <div class="text">
        <p class="split-heading">
          Aligned to the following <span class="bold">AIR</span> Indicators:
        </p>
        <ul>
          <li>{{AIR_Indicators}}</li>
        </ul>
      </div>
      <div class="text">
        <p class="split-heading">
          Aligned to the following <span class="bold">Standards of Mathematical Practice:</span>
        </p>
        <ul>
          <li>{{SMP}}</li>
        </ul>
      </div>
    </div>
      <div class="purpose heading">
        <h3>Purpose</h3>
      </div>
      <div class="purpose text">
        <p>
          {{Purpose}}
        </p>
      </div>
    <div class="process heading">
      <h3> Process </h3>
    </div>

    <div class="bottom-container text">
        <div class="cube">
          <h4>Instructional Practice</h4>
          <center><h3> {{IP}} </h3> </center> </br>
          <p><span class="description">What</span> {{What}} </p></br>
          <p><span class="description">When</span> {{When}} </p></br>
          <p><span class="description">How</span> {{How}} </p></br>
        </div>
    </div>
{{/each}}
</div>
</script>

最终,“IP”、“What”、“When”和“How”将在文档下半部分的“Process”标题下看起来像这样 http://imgur.com/rV4PIFC

这是我正在使用的 JS Fiddle: http://jsfiddle.net/rr9Vz/

更新

我刚刚尝试过这样的事情

  var ips = [];
   for(var i in igListOrig) {
            var ip = igListOrig[i].IP + igListOrig[i].What + igListOrig[i].When +                     
            igListOrig[i].How ;
            if($.inArray(ip,ips)== -1 ){
                ips.push(ip);
            }
        }

我得到了我需要的数组,但现在如何在把手中传递我的模板和这个迭代?

更新 2

出于所有意图和目的,&lt;div class='bottom-container text&gt; 在 Handlebars 编译时需要看起来像这样。

<script id="template" type="text/x-handlebars-template">
   <div class="container">
    <div class='titles'>
      <div class="left">Aspire Logo</div>
      <div class="middle">{{IG}}</div>
      <div class="right">Common Core</div>
      <div class="purple"></div>
    </div>
    <div class="split">
      <div class="text">
        <p class="split-heading">
          Aligned to the following <span class="bold">AIR</span> Indicators:
        </p>
        <ul>
          <li>{{AIR_Indicators}}</li>
        </ul>
      </div>
      <div class="text">
        <p class="split-heading">
          Aligned to the following <span class="bold">Standards of Mathematical Practice:</span>
        </p>
        <ul>
          <li>{{SMP}}</li>
        </ul>
      </div>
    </div>
      <div class="purpose heading">
        <h3>Purpose</h3>
      </div>
      <div class="purpose text">
        <p>
          {{Purpose}}
        </p>
      </div>
    <div class="process heading">
      <h3> Process </h3>
    </div>  
  <div class="bottom-container text">
    <div class="cube">
      <h4>Instructional Practice</h4>
      <center><h3> Problem Solving</h3> </center> </br>
      <p><span class="description">What</span> PoWs are complex problems. </p></br>
      <p><span class="description">When</span> PoWs should be administered once per month. </p></br>
      <p><span class="description">How</span> 1.Introduce problem, process, and rubric. 2.Students are given time in class to work on problem throughout the week. 3.Students complete write up. 4.Student peer edit write up. 5.Students revise write up</p></br>
    </div>
    <div class="cube">
      <h4>Instructional Practice</h4>
      <center><h3> Problem of the Month (POM) </h3> </center> </br>
      <p><span class="description">What</span> The POMs are divided into five levels. Students are asked to explain their solutions and reasoning in a write up. </p></br>
      <p><span class="description">When</span> Students should work on problem the first 10-15 minutes of a period for 5-7 consecutive days. </p></br>
      <p><span class="description">How</span> Write them on a pieces of paper. </p></br>
    </div>
    <div class="cube">
      <h4>Instructional Practice</h4>
      <center><h3> Formative Assessment Lesson (FAL) </h3> </center> </br>
      <p><span class="description">What</span> FALs consist of 3 parts including a pre-assessment (approximately 15 min. </p></br>
      <p><span class="description">When</span> The 3 part cycle is intended to be given approximately two-thirds the way into a unit of study. </p></br>
      <p><span class="description">How</span> 1.Pre assessment. 2.Introduce activity. 3.Students work collaboratively. 4.Whole class discussion/ presentation. 5.Post assessment. </p></br>
    </div>
    <div class="cube">
      <h4>Instructional Practice</h4>
      <center><h3> Mathematics Assessment Resources (MARS)</h3> </center> </br>
      <p><span class="description">What</span> Story Problems. </p></br>
      <p><span class="description">When</span> Done at the begining of the unit. </p></br>
      <p><span class="description">How</span> After each asssessment. </p></br>
    </div>
 </div>
</div>

我想要这个:http://jsfiddle.net/8Xnpk/1/

但我得到了这个:http://jsfiddle.net/rr9Vz/3/

@MarcoCl 的解决方案在代码执行方面有效,但无论什么时候,我似乎都无法得到这个http://jsfiddle.net/8Xnpk/1/

【问题讨论】:

    标签: javascript jquery json handlebars.js


    【解决方案1】:

    为了避免重复,请使用字典而不是数组:这样可以加快重复查找速度,并且不会损害您当前的代码。

    function filterDuplicates(array){
      // this will hold the new filtered dictionary
      var uniqArray  = [],
      // this is used for the lookup
          dupCheck = {};
      for( var i=0; i< array.length; i++){
        var entry = array[i];
        var uniqueKey = entry.IP + entry.What + entry.When + entry.How;
        if(!dupCheck[uniqueKey]){
          // here there are only unique values
          dupCheck[uniqueKey] = true;
          uniqArray.push(entry);
        }
      }
      return uniqArray;
    }
    
    var source = $("#template").html();
    var template = Handlebars.compile(source);
    var igListOrig = [...];
    
    $('body').append(template(filterDuplicates(igListOrig)));
    

    作为替代方案,您可以将 filterDuplicates 逻辑集成到自定义 Handlebar 帮助程序中。

    {{#each this}} 标记替换为自定义{{€#eachUnique this}} 之一:

    <script id="template" type="text/x-handlebars-template">
      <div class="container">
        {{#eachUnique this}}
        ...
        {{/eachUnique}}
      </div>
    </script>
    

    然后注册新的助手:

    Handlebars.registerHelper('eachUnique', function(array, options) {
      // this is used for the lookup
      var  dupCheck = {};
      // template buffer
      var buffer = '';
      for( var i=0; i< array.length; i++){
        var entry = array[i];
        var uniqueKey = entry.IP + entry.What + entry.When + entry.How;
        // check if the entry has been added already
        if(!dupCheck[uniqueKey]){
          // here there are only unique values
          dupCheck[uniqueKey] = true;
          // add this in the template
          buffer += options.fn(entry);
        }
      }
      // return the template compiled
      return buffer;
    });
    

    更新 2

    这个问题与原来的问题有点不同 - 它只是从列表中删除重复项,它变成了一个与模板相关的问题......

    我将留下重复的答案并添加另一个以进行第二次更新:

    预处理您的数据以删除公共数据:

    var source = $("#template").html();
    var template = Handlebars.compile(source);
    var igListOrig = [...];
    
    var newModel = {
      'IG': igListOrig[0].IG,
      'AIR_Indicators': igListOrig[0].AIR_Indicators,
      'SMP': igListOrig[0].SMP, 
      'Purpose':igListOrig[0].Purpose ,
      entries: igListOrig
    };
    $('body').append(template(newModel));
    

    新模板将如下所示:

    <script id="template" type="text/x-handlebars-template">
      <div class="container">
        <div class='titles'>
        <div class="left">Aspire Logo</div>
        <div class="middle">{{IG}}</div>
      <div class="right">Common Core</div>
      <div class="purple"></div>
    </div>
    <div class="split">
      <div class="text">
        <p class="split-heading">
          Aligned to the following <span class="bold">AIR</span> Indicators:
        </p>
        <ul>
          <li>{{AIR_Indicators}}</li>
        </ul>
      </div>
      <div class="text">
        <p class="split-heading">
          Aligned to the following <span class="bold">Standards of Mathematical Practice:</span>
        </p>
        <ul>
          <li>{{SMP}}</li>
        </ul>
      </div>
    </div>
      <div class="purpose heading">
        <h3>Purpose</h3>
      </div>
      <div class="purpose text">
        <p>
          {{Purpose}}
        </p>
      </div>
    <div class="process heading">
      <h3> Process </h3>
    </div>  
    <div class="bottom-container text">
    // use eachUnique here instead of each to avoid duplicates
      {{eachUnique items}}
        <div class="cube">
          <h4>Instructional Practice</h4>
          <center><h3>{{IP}}</h3> </center> </br>
          <p><span class="description">What</span> {{What}} </p></br>
          <p><span class="description">When</span> {{When}}</p></br>
          <p><span class="description">How</span> {{How}}</p></br>
        </div>
      {{/eachUnique}}
     </div>
    </div>
    </script>
    

    【讨论】:

    • @MarcoCl,感谢您的回复。我尝试了您的第一个解决方案,但仍然留下重复的表格。我试图在`
      中以一种形式获取“IP”、“What”、“When”和“How”。这是带有您的代码jsfiddle.net/rr9Vz/3 的 JS Fiddle 在您的第二个解决方案中,我尝试阅读有关助手的文档,但对于在模板中添加“eachUnique”的位置仍然有些困惑。感谢您的帮助。
    • 关于如何解决此问题的任何其他想法?
    • 您正在使用 4 个“字段”来查找重复项:“IP”+“什么”+“何时”+“如何”。快速浏览一下,“什么”字段与所有条目不同:每个条目的键都不同,这就是它不过滤的原因。
    • 抱歉再次打扰,我再次使用了过滤器助手,它给了我错误:TypeError: object is not a function, at line `buffer += fn(entry).希望你能再看看。所以我澄清了这个问题。你是绝对正确的,对于“IP”、“What”、“When”和“How”,键会有所不同,这就是我需要的预期回报。但是如果不重复按键,我无法让它们并排显示在 div 中,谢谢,我希望你能再看看它。
    • 没错:fn 是第二个参数的属性,而不是函数本身。更新了代码。
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签