0

我最近使用 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],
    }]

希望我能做到,因为它更容易循环。

4

1 回答 1

0

我认为这是想要的效果,还请记住,当使用Array.prototype.filter并且没有元素通过测试时,返回的值将是,[]如果您尝试访问该[][0]元素,则该值将是undefined从该undefined值开始,它将引发错误。

例如,如果您尝试访问沃尔沃的价格,它将引发错误Cannot read property 'price' of undefined,因为沃尔沃不存在于PriceArray

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)

于 2018-06-13T07:20:58.787 回答