【问题标题】:Display an object as a list将对象显示为列表
【发布时间】:2020-03-22 00:22:29
【问题描述】:

我有一个对象:

cars: {
    number': 1, 'overload': 1,'brand': {'0': {'porsche': [{'price': 10, 'id': 0}],'vw': [{'price': 20, 'id': 1}]}}},

我想将其显示为列表(第一个键的示例)

Number : 1
Overload : 1
Brand:
Porsche: 
price: 10
id: 0
vw:
price: 20
id: 1

我该怎么做?

【问题讨论】:

  • 到目前为止你尝试过什么?
  • Object.entries , object.keys 但没有结果
  • 请添加涉及Object.keysObject.entries 的代码,这些代码无法创建minimal reproducible example
  • 但是我在对象中有数组,我想在另一行显示

标签: javascript vue.js


【解决方案1】:

下面的代码将显示您想要的我的想法,但就灵活性而言,您可以创建子组件并将项目作为道具传递以获得更多控制权。我只是想以一种简单的方式说明你在 Vue 中实际需要做什么来迭代你的结构......

new Vue({
  el: '#app',
  data() {
    return {
      obj: {"0":{"color":[{"red":1,"value":100}],"brand":[{"id":0,"price":100}]},
            "1":{"color":[{"blue":1,"value":100}],"brand":[{"id":0,"price":100}]},
            "2":{"color":[{"green":1,"value":100}],"brand":[{"id":0,"price":100}]},
            "3":{"color":[{"yellow":1,"value":100}],"brand":[{"id":0,"price":100}]},
          },
    };
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div v-for='(value,id) in obj' :key='id'>
    <div v-for='(rowvalue,rowid) in value' :key='rowid'>
      {{rowid}}
      <div v-for='(subvalue,subid) in rowvalue' :key='subid'>
        <div v-for='(listvalue,listid) in subvalue' :key='listid'>
          {{listid}} : {{listvalue}}
        </div>
      </div>
    </div>
  </div>
</div>

这个显示:

color
red : 1
value : 100
brand
id : 0
price : 100
color
blue : 1
value : 100
brand
id : 0
price : 100
color
green : 1
value : 100
brand
id : 0
price : 100
color
yellow : 1
value : 100
brand
id : 0
price : 100

我会留下您可能想要做的实际格式和其他方面,希望对您有所帮助。

【讨论】:

  • @TheDevGuy 你已经改变了你的问题,所以 json 不再匹配 - 但问题仍然得到回答......同样的过程将适用。
【解决方案2】:

我认为你正在寻找的是

obj = {"0":{"color":[{"red":1,"value":100}],"brand":[{"id":0,"price":100}]},
 "1":{"color":[{"blue":1,"value":100}],"brand":[{"id":0,"price":100}]},
 "2":{"color":[{"green":1,"value":100}],"brand":[{"id":0,"price":100}]},
 "3":{"color":[{"yellow":1,"value":100}],"brand":    [{"id":0,"price":100}]}
}
Object.keys(obj).forEach(function(key,index) {
  // key: "0", "1", "2", "3" in your case
  console.log(obj[key])
});

你也可以这样做

for (var key in obj) {
   console.log(obj[key])
}

这将为您提供您想要的具有“颜色”和“品牌”属性的对象

【讨论】:

  • 如何在 Vue 中按我想要的方式显示?
  • 是的,差不多了,但我的对象出错了。我更新代码
猜你喜欢
  • 2016-05-08
  • 2018-10-20
  • 1970-01-01
  • 1970-01-01
  • 2017-12-01
  • 1970-01-01
  • 2011-07-07
  • 1970-01-01
  • 2013-11-22
相关资源
最近更新 更多