在嵌套的forEach循环中传递变量

时间:2019-07-04 16:47:06

标签: javascript

我想列出一些产品及其变体。差异位于产品对象上的数组中。为了显示它们,我已经考虑过做一个嵌套的.forEach()(不确定是否最好),但是,我需要将项目对象传递给嵌套的forEach循环才能正确显示它们,即将标题与变体名称连接在一起。我已经创建了一个示例。

const products = [{
  "title": "T-Shirt",
  "options": [{
    "name": "Colour",
    "values": [{"value": "Blue"}]
  }, {
    "name": "Size",
    "values": [{"value": "Large"}]
  }, {
    "name": "Colour",
    "values": [{"value": "Red"}]
  }]
}, {
  "title": "Hoodie",
  "options": [{
    "name": "Colour",
    "values": [{"value": "Blue"}]
  }, {
    "name": "Colour",
    "values": [{"value": "White"}]
  }]
}]

products.forEach(function (product, index) {
  product.options.forEach(function (option) {
  if (option.name === 'Colour') {
    const container = document.createElement("div");  
    const content = document.createTextNode(`-${option.values[0].value}`); 
     container.appendChild(content); 
     document.querySelector('.current').append(container)
   }
 })
})
<h2>Current</h2>
<div class="current"></div>

<h2>Desired</h2>
<div class="desired">
  <div>T-Shirt-Blue</div>
  <div>T-Shirt-Red</div>
  <div>Hoodie-Blue</div>
  <div>Hoodie-White</div>
</div>

我该怎么做?或者,是否有更理想的解决方案?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

不确定是错字还是忘记了${product.title}前缀。

这应该获得预期的结果:

const content = document.createTextNode(`${product.title}-${option.values[0].value}`);

您的运行示例:

const products = [
  {
    "title": "T-Shirt",
    "options": [
      {
        "name": "Colour",
        "values": [
          {
            "value": "Blue"
          }
        ]
      },
      {
        "name": "Size",
        "values": [
          {
            "value": "Large"
          }
        ]
      },
      {
        "name": "Colour",
        "values": [
          {
            "value": "Red"
          }
        ]
      }
    ]
  },
    {
    "title": "Hoodie",
    "options": [
      {
        "name": "Colour",
        "values": [
          {
            "value": "Blue"
          }
        ]
      },
      {
        "name": "Colour",
        "values": [
          {
            "value": "White"
          }
        ]
      }
    ]
  }
]

products.forEach(function (product, index) {
  product.options.forEach(function (option) {
  if (option.name === 'Colour') {
    const container = document.createElement("div");  
    const content = document.createTextNode(`${product.title}-${option.values[0].value}`); 
     container.appendChild(content); 
     document.querySelector('.current').append(container)
   }
 })
})
<h2>
Current
</h2>
<div class="current">
</div>

<h2>
Desired
</h2>
<div class="desired">
  <div>
  T-Shirt-Blue
  </div>
  <div>
  T-Shirt-Red
  </div>
  <div>
  Hoodie-Blue
  </div>
  <div>
  Hoodie-White
  </div>
</div>