英文:
Iterating through object with key/value map
问题
从REST API获取的对象如下所示:
response = {
"0": [
{
"description": "basket",
"color": "red"
},
{
"description": "pillow",
"color": "blue"
},
{
"description": "armchair",
"color": "white"
}
],
"1" : [
{
"description": "shirt",
"color": "black"
},
{
"description": "pants",
"color": "blue"
}
]
}
这是我需要在我的视图中显示的内容。
在controller.js
中,您可以使用以下代码:
self.catKeys = Object.keys(response);
self.catValue = Object.values(response);
在view.html
中,您可以使用以下代码:
<div ng-repeat="cat in ctrl.catKeys" class="col-md-3">{{ cat }}</div>
<div ng-repeat="val in ctrl.catValue" class="col-md-9">
<div ng-repeat="item in val">
{{ item.description }} {{ item.color }}
</div>
</div>
希望这对您有所帮助。如果有其他问题,请随时提问。
英文:
From the rest api, I get an object like this:
response = {
"0": [
{
"description": "basket",
"color": "red"
},
{
"description": "pillow",
"color": "blue"
},
{
"description": "armchair",
"color": "white"
}
],
"1" : [
{
"description": "shirt",
"color": "black"
},
{
"description": "pants",
"color": "blue"
}
]
}
This is what I need to display in my view:
// controller.js
self.catKeys= Object.keys(response)
self.catValue= Object.values(response)
// view.html
<div ng-repeat="cat in ctrl.catKeys" class="col-md-3"> {{ cat }} </div>
<div ng-repeat="val in ctrl.catValue" class="col-md-9">
{{ val[index].description }} {{ val[index].color}}
</div>
I've also tried many other things but I just cannot get it..please help
答案1
得分: 3
使用Array#map
将每个项目与其颜色连接起来,然后使用join
将它们组合成一个字符串。
for (const [k, v] of Object.entries(response)) {
response[k] = v.map(x => x.color + ' ' + x.description).join(' - ');
}
self.response = response;
然后,显示很简单:
<div ng-repeat="(k, v) in ctrl.response" class="row">
<div class="col-md-3">{{k}}</div>
<div class="col-md-9">{{v}}</div>
</div>
英文:
You can use Array#map
to concatenate each item with its color, then join
it into one string.
for (const [k, v] of Object.entries(response)) {
response[k] = v.map(x => x.color + ' ' + x.description).join(' - ');
}
self.response = response;
Then, displaying is simple:
<div ng-repeat="(k, v) in ctrl.response" class="row">
<div class="col-md-3">{{k}}</div>
<div class="col-md-9">{{v}}</div>
</div>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论