这就是我想要做的。 我有这样的对象数组。
[
{productOptionId: 1, value: "Black"},
{productOptionId: 1, value: "Red"},
{productOptionId: 2, value: "UK 43"},
{productOptionId: 2, value: "FIJI 1"},
]
我想基于'productOptionId'对该数组的元素进行分组,并基于这些组显示选择框。并且还可以使用这些子数组来显示相应选择框的选项。
打字稿代码:
var i=0;
var result = [];
var object = [];
var objects = [
{productOptionId: 1, value: "Black"},
{productOptionId: 1, value: "Red"},
{productOptionId: 2, value: "UK 43"},
{productOptionId: 2, value: "FIJI 1"},
];
var k = -1;
for (var i = 0; i < objects.length; i++){
if(k!=objects[i].productOptionId){
k = objects[i].productOptionId;
object = []
object.push(objects[i]);
result.push(Array.from(object));
}else{
object.push(objects[i]);
}
}
this.allOptionValues = Array.from(result);
HTML代码:
<p *ngFor="let productOption of allOptionValues" >
<select >
<option *ngFor="let optionValue of productOption.values" >{{optionValue.value}}</option>
</select>
</p>
预期输出:
答案 0 :(得分:0)
<p *ngFor="let productOption of allOptionValues | keyvalue">
<select>
<option *ngFor="let optionValue of productOption.value" >{{optionValue.value}}</option>
</select>
</p>
constructor() {
this.makeProductGroup();
}
makeProductGroup() {
var objects = [
{productOptionId: 1, value: "Black"},
{productOptionId: 1, value: "Red"},
{productOptionId: 2, value: "UK 43"},
{productOptionId: 2, value: "FIJI 1"},
];
const newProductArray = {};
const uniqueProductId = [];
for (var i = 0; i < objects.length; i++) {
if (uniqueProductId.indexOf(objects[i].productOptionId) === -1) {
uniqueProductId.push(objects[i].productOptionId);
newProductArray[objects[i].productOptionId] = [];
}
newProductArray[objects[i].productOptionId].push(objects[i]);
}
this.allOptionValues = newProductArray;
}
makeProductGroup()函数使对象类似于下面的对象,因此我们将键值管道用于对象中的循环。
{
"1": [
{
"productOptionId": 1,
"value": "Black"
},
{
"productOptionId": 1,
"value": "Red"
}
],
"2": [
{
"productOptionId": 2,
"value": "UK 43"
},
{
"productOptionId": 2,
"value": "FIJI 1"
}
]
}