【问题标题】:How to get the object and display in html javascript如何获取对象并以 html javascript 显示
【发布时间】:2019-05-24 07:30:04
【问题描述】:

我想知道如何在 javascript 中迭代对象数组。

我有一个数组 sample,其中属性 options 应该以 lit-HTML 显示每个对象


var sample = [{
  "trans": [{
    "id": "trans",
    "fee": 20,
    "options": ["credit", "debit"]
  }],
  "insta": [{
    "id": "insta",
    "fee": 30,
    "options": ["bank", "credit"]
  }]
}]

render(){
  sample.map((r)=>{
   <select>
     r.options.map((e)=>
      return html`

          <option>${e.options}</option>
     `
     )
   </select>
  }
}

【问题讨论】:

  • 那是什么模板框架?请为其添加标签。
  • @Barmar 感谢您的回复,点亮元素,我已添加标签

标签: javascript html arrays object lit-element


【解决方案1】:

我认为您在这里需要的是这样的(您缺少渲染函数中的返回):

var sample=[{
  "trans":[{
   "id": "trans",
   "fee": 20,
  "options": ["credit", "debit"]
 }],
  "insta":[{
   "id": "insta",
   "fee": 30,
   "options":["bank", "credit"]
}]
}]

render(){
   return sample.map((r)=>{
   <select>
     r.options.map((e)=>
      return html`

          <option>${e.options}</option>
     `
     )
   </select>
  }
}

【讨论】:

    【解决方案2】:

    您将Array.map 应用于r.options,因此每个元素已经是一个选项,因此您只需调用

    r.options.map( e => html`<option>${e}</option>`)
    

    【讨论】:

    • 感谢回复,我有一个示例 obj,其中包含两个不同的对象数组 transinsta stil 可以使用 map 吗??
    • 是的,你可以使用obj.trans.map()obj.insta.map()分别进入optionsobj.trans.options.map()
    【解决方案3】:

    e 已经是options 数组元素的值,不需要使用e.options。所以应该是

    <option>${e}</option>
    

    您还需要循环遍历r.trans.optionsr.insta.options

    render(){
      sample.map((r)=>{
       <select>
         r.trans.options.map((e)=>
          return html`
    
              <option>${e}</option>
         `
         )
       </select>
       <select>
         r.insta.options.map((e)=>
          return html`
    
              <option>${e}</option>
         `
         )
       </select>
      }
    }
    

    【讨论】:

    • 感谢回复,因为我有两个不同的数组对象transinsta,我的问题仍然是如何使用map 和dsiplay 选项
    • 我没有看到额外的嵌套级别。你能用纯 HTML 展示你期望的最终结果吗?它们总是相同的键 transinsta,还是动态的?
    • 相同的键 transinsta 总是,预期结果是,对于每个对象数组,应在选择标签中填充相应的 options
    • transinsta 中的选项相同。你想为每个键单独的&lt;select&gt; 吗?
    • 选项不一样,请检查sample,对于trans,选择标签应该有两个选项"credit", "debit",对于insta,选择标签应该有两个选项"bank", "credit",`是的,对于每个对象,我需要为每个键设置单独的
    猜你喜欢
    • 2021-03-04
    • 2013-06-04
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 2019-10-16
    相关资源
    最近更新 更多