在另一个ForEach中创建一个forEach

时间:2018-03-06 17:25:33

标签: javascript arrays node.js foreach ejs

我必须从json文件(实际上是2个json文件)做一个ForEach因为这个原因我做2 forEach,代码是

<head>
<style>
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}

tr:nth-child(even) {
    background-color: #dddddd;
}
</style>
</head>
<body>

<h2>HTML Table</h2>

<table>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>


<% alist.forEach(function(alist_items){%>

  <% alist_b.forEach(function(alist_items_b){%>
  <%if(alist_items_b.AY==alist_items.CI){ %>
  <tr>
  <td bgcolor="#FF0000"><%= JSON.stringify(alist_items_b) %></td>
  </tr>
  <% }else{ %>
  <tr>
  <td><%= JSON.stringify(alist_items_b) %></td>
  <% } %>
  </tr>

<% }) %> 
<% }) %>
</table>

json文件是:

[
  {
    "CI": "10"
  },
  {
    "CI": "11"
  },
  {
    "CI": "12"
  },
  {
    "CI": "13"
  },
  {
    "CI": "14"
  },
  {
    "CI": "15"
  },
  {
    "CI": "16"
  },
  {
    "CI": "17"
  },
  {
    "CI": "18"
  },
  {
    "CI": "19"
  },
  {
    "CI": "20"
  }
]

[\[
  {
    "AY": "10"
  },
  {
    "AY": "11"
  },
  {
    "AY": "12"
  },
  {
    "AY": "13"
  },
  {
    "AY": "14"
  }

我需要以红色显示重复值,通常是其他值,但是如何在1图片中看到,其他值重复重复多少次。 我需要只展示一次其他人的价值

由于

1 个答案:

答案 0 :(得分:1)

好的!首先,我们将对象数组合并为一个。其次,迭代合并的数组并检查重复值(它的工作方式类似于哈希映射)。第三,在名为colorRed的每个对象中插入一个新属性(它表示是否将重复的行着色为红色)。

JS改变:

var a = []; //first array of object
var b = []; //second array of object
Array.prototype.push.apply(a, b); //merging both the arrays

//finding the number of occurences of all the values
//variable would hold all the indexes of the array having same value
var c = new Object();
a.forEach(function (value, index) {
     var vArr = Object.keys(value);
     if (!c.hasOwnProperty(value[vArr[0]]))
        c[value[vArr[0]]] = [];
     c[value[vArr[0]]].push(index);
     c[value[vArr[0]]].forEach(function (cValue, cIndex) {
        if (c[value[vArr[0]]].length > 1)
           a[cValue].colorRed = true;
        else
           a[cValue].colorRed = false;
     });
});

现在,在JS中进行了更改。在模板中迭代的数组只是对象数组,包含是否将行绘制为红色。为了更好地理解,您只需执行console.log(a);并检查最终的数组结构。

HTML更改:

<% a.forEach(function(val, ind) { %>
<tr>
    <%if (val.colorRed) { %>
        <td bgcolor="#FF0000">
    <% } else { %>
        <td>
    <% } %>
    <%= JSON.stringify(val) %></td>
</tr>
<% }) %>