我正在研究使用映射功能更改数据的数组。我有一系列图标,如下所示。
private socialIcons:any[] = [
{"icon":"thumbs-up","operation":"like"},
{"icon":"thumbs-down","operation":"unlike"},
{"icon":"eye","operation":"view"},
{"icon":"text","operation":"comment"},
];
上面是我将传递到子组件中的图标数组。我正在使用服务调用从后端检索数据。我正在使用地图更改数据,如下所示。
this.esServices.loadEsdata(obj).pipe(map(res=>res.json())).subscribe(res=>{
res.map(x=>{
x["socialIcons"] = this.socialIcons
x["socialIcons"].map(icon=>{
switch(icon.operation){
case 'like':{
icon["value"] = x["nooflikes"]
break;
}
case 'unlike':{
icon["value"] = x["nooflikes"]
break;
}
case 'view':{
icon["value"] = x["views"]
break;
}
case 'comment':{
icon["value"] = x["noofcomments"]
break;
}
}
})
console.log(x)
return x;
}),
this.datacount = res.length;
this.creatives = this.creatives.concat(res);
})
问题在于,在res中,第二个元素的... x [“ socialIcons”]覆盖第一个元素的x [“ socialIcons”]。更加清楚。 第一个元素的控制台输出 预期输出:
[0:{
resource_name: "potterypainting_40.jpg"
socialIcons: Array(4)
0: {icon: "thumbs-up", operation: "like", value: 1}
1: {icon: "thumbs-down", operation: "unlike", value: 1}
2: {icon: "eye", operation: "view", value: 0}
3: {icon: "text", operation: "comment", value: 0}
length: 4
}]
注意:同样使用断点进行检查,我在第一次迭代中获得了预期的输出,但是随着第二次迭代开始,第一次迭代中获得的array的值将被第二次迭代的值覆盖,如下所示。因此,两个元素中的socailIcon数组将相同,这是错误的。 获得输出
[0:{
resource_name: "potterypainting_40.jpg"
socialIcons: Array(4)
0: {icon: "thumbs-up", operation: "like", value: 0}
1: {icon: "thumbs-down", operation: "unlike", value: 0}
2: {icon: "eye", operation: "view", value: undefined}
3: {icon: "text", operation: "comment", value: 0}
length: 4
}]
控制台输出第二个元素
[1:{
resource_name: "streetart_41.jpg"
socialIcons: Array(4)
0: {icon: "thumbs-up", operation: "like", value: 0}
1: {icon: "thumbs-down", operation: "unlike", value: 0}
2: {icon: "eye", operation: "view", value: undefined}
3: {icon: "text", operation: "comment", value: 0}
length: 4
}]
观察到两者的resource_name是不同的,但只有socialIcons会被最新的覆盖。
请让我知道我要去哪里了。
答案 0 :(得分:0)
map
运算符不是这样的。
您必须将其分配给某些东西。
尝试一下:
x['socialIcons'] = this.socialIcons;
x['socialIcons'] = x['socialIcons'].map(icon => { // This line
switch (icon.operation) {
case 'like': {
icon['value'] = x['nooflikes'];
break;
}
case 'unlike': {
icon['value'] = x['nooflikes'];
break;
}
case 'view': {
icon['value'] = x['views'];
break;
}
case 'comment': {
icon['value'] = x['noofcomments'];
break;
}
}
});