遍历Handlebars中JSON对象重复项

4

我在我的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”、“What”、“When”和“How”,并忽略所有重复项。在每次迭代后,只有“IP”、“What”、“When”和“How”是不同的。我需要保留这些差异并忽略其他重复项。
我参考了类似于这样的内容,但我认为这个人的情况有点不同。 遍历JSON对象 最终,这将放在一个handlebars模板中,如下所示。
<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);
            }
        }

我得到了所需的数组,但现在如何在handlebars中同时传递我的模板和迭代?
更新2:就所有目的而言,“

我希望得到这个: http://jsfiddle.net/8Xnpk/1/

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

@MarcoCl的解决方案在代码执行方面有效,但出于某种原因,我似乎无法获得这个http://jsfiddle.net/8Xnpk/1/

1个回答

3
为了避免重复,使用字典而不是数组:这会加快查找重复项的速度,并且不会影响您当前的代码。
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助手中。
用自定义的“{{€#eachUnique this}}”标签替换“{{#each 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,感谢您的回复。我尝试了您的第一个解决方案,但仍然存在重复的表单。我正在尝试在<div class="bottom-container text">中将“IP”、“What”、“When”和“How”全部放入一个表单中。这是带有您代码的JS Fiddle http://jsfiddle.net/rr9Vz/3/。在您的第二个解决方案中,我尝试阅读有关helpers的文档,但仍然对在模板中添加“eachUnique”的位置有些困惑。感谢您的帮助。 - gary1410
您正在使用4个“字段”查找重复项:“IP”+“What”+“When”+“How”。从快速查看中,“What”字段在所有条目中都不同:因此每个条目的键将不同,这就是为什么它无法过滤的原因。 - MarcoL
抱歉再次打扰,我再次使用了过滤器助手,但出现了错误:TypeError: object is not a function,在第buffer += fn(entry)行。希望您能再次查看一下。所以我澄清了问题...您是绝对正确的,键将不同,对于“IP”,“What”,“When”和“How”,这就是我需要的预期返回。但是我无法让它们在div旁边并排显示而不重复键,谢谢,希望您能再次查看它。 - gary1410
没错:fn是第二个参数的一个属性,而不是函数本身。已更新代码。 - MarcoL
嘿@MarcoCI,再次感谢你的帮助。我再次运行了代码,它是正确的,但结果不是我期望的。我更新了问题,其中写着“已更新2”。希望这能澄清事情。我感觉我们快要成功了!非常感激你迄今为止的帮助。 :) - gary1410
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接