[英]rxjs/Angular2 Loop but show different object of a single associative array
我最近使用rxjs合並了兩個數組
MyArray = [{
"Field": ["Cars"],
"Type": ["BMW", "Toyota", "Volvo"]
},
{
"Field": ["House"],
"Type": ["Condominium", "TownHouse"],
}
PriceArray = [
{
field: Cars,
distribution: [{"name" : "BMW","price":2},{"name" : "Toyota","price":3}]
},
{
field: People,
distribution: [{"name" : "Condominium","price":3},{"name" : "TownHouse","price":2}]
}]
使用rxjs過濾器
const $MergeData = MyArray.map(val => {
return Object.assign({}, val,this.PriceArray.filter(v => v.Field === val.field)[0])
});
this.mergedArray = $MergeData;
現在看起來這個
mergedArray = [{
"Field": "Cars",
"Type": ["BMW", "Toyota", "Volvo"],
"field" : "Cars",
"distribution" : [
{
"name" : "BMW"
"price": 2 ,
},
{
"name" : "Toyota"
"price": 3 ,
},
{
"name" : "Toyota"
"price": 4 ,
}
]
}, .... (house array here)];
然后我試圖顯示該項目的價格,但它不起作用
<div *ngFor="let item of mergedArray">
<div *ngFor="let car of item.Field; let i = index">
<p>{{car}} </p>
<p>{{item.distribution.price[i]}} </p>
</div>
</div>
我希望修復或更好,如果數組應該看起來像這樣
mergedArray = [{
"Field": "Cars",
"Type": ["BMW": 2, "Toyota" : 3, "Volvo" : 4],
}]
希望我可以,因為它更容易循環。
我認為這是理想的效果,還請記住,當使用Array.prototype.filter
且沒有任何元素通過測試時,返回值將為[]
,如果您嘗試訪問[][0]
元素,則該值將是undefined
,之后,如果您嘗試從該undefined
值訪問某些屬性,它將引發錯誤。
例如,如果您嘗試訪問Volvo的價格,它將拋出錯誤Cannot read property 'price' of undefined
,因為PriceArray
中不存在Volvo
let priceArray = [ { "name" : "BMW", "price": 2 }, { "name" : "Toyota", "price": 3 }, { "name" : "Toyota", "price": 4 } ]; let myArray = [{ "Field": "Cars", "Type": ["BMW", "Toyota", "Volvo"]}] let findPrice= (priceArray,mark)=> priceArray .find(x=> x.name === mark) ? priceArray.find(x=> x.name === mark).price : 'No data' let mergedArray = myArray[0].Type.map(x=> ({[x]:findPrice(priceArray,x)})) console.log(mergedArray)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.