Angular 5 - 通过ArrayList迭代特定的键值

时间:2018-02-14 07:15:27

标签: json angular typescript arraylist

  

如何遍历我的arrayList并返回特定的键   值?我的数据是在   Json格式为   如下:

[
    {
        "id": 1,
        "name": "Albany",
        "manufacture": "Albany Superior Low Gi Sliced Brown Seed Bread 700g",
        "price": 15.49,
        "category": "Food",
        "type": "Breads",
        "image": "data:image/jpeg;base64,/9j/4AAQSkZJRgA..."
    },
    {
        "id": 2,
        "name": "Blue Ribbon",
        "manufacture": "Blue Ribbon Brown Plus Low Gi Bread 700g",
        "price": 13.99,
        "category": "Food",
        "type": "Breads",
        "image": "data:image/jpeg;base64,/9j/4AAQSkZJRgABA..."
    },
    {...},
    {...},
    ...
]
  

我能够返回以下数据:

enter image description here

  

我已经编写了以下代码来获取单个产品   型乳

@Component({
  selector: 'app-milk-cream',
  templateUrl: './milk-cream.component.html',
  styleUrls: ['./milk-cream.component.css']
})
export class MilkCreamComponent implements OnInit {

  allProducts: Array<Product> = [];
  quantity: number = 1;
  resultArray:any;

  constructor( private prod: ProductService) { }

  CallbackFunctionToFindTypeById(prod) {
    return prod.type === 'Milk';
  }

  ngOnInit() {

    this.allProducts = JSON.parse(localStorage.getItem('product-data') );
    //console.log( JSON.stringify( this.allProducts ) );

    var productMilk = this.allProducts.find(this.CallbackFunctionToFindTypeById);
    console.log( productMilk );
  }
}

interface Product {
  id: number;
  name: string;
  manufacture: string;
  price: number;
  category: string;
  type: string;
  image: string;
}
  

然后我编辑了CallbackFunctionToFindTypeById方法,让它循环   并返回一个带有Milk类型产品的arrayList;问题是我无法在ngOnInit中调用该方法(不确定它是否也有效):

CallbackFunctionToFindTypeById(prod) {

    for (var i=0; i < this.allProducts.length; i++){
      if ( prod.type === 'Milk' ){
        this.allProducts[i];
      }
    }
    return this.allProducts;
  }
  

有人可以协助,我是Angular 5typescript的新人   {{3}} ...

1 个答案:

答案 0 :(得分:2)

您应该使用filter返回数组中与谓词相关的所有项

var productMilk = this.allProducts.filter(item => item.type === 'Milk');