【问题标题】:How to get an object with its ID?如何获取带有 ID 的对象?
【发布时间】:2019-09-18 14:06:12
【问题描述】:

我正在创建一个食物应用程序,我们可以定制像地铁这样的食物。感谢他们的 ID,我将物品(如三明治或意大利腊肠)及其配料(如芥末或烧烤)保存在购物车中。

我的购物车中的数据是这样保存的:

menuSelection: MenuSelection = {
  id: 0,
  supp: [1123],
};

菜单如下所示:

  products: Menu[] = [
    {
        id: 0, name: 'Salami', price: 8, hour: null,
        supp:[
          { id: 1123, name: 'fromage', price: 5, hour: null },
          { id: 11234, name: 'bbq', price: 10, hour: null },
        ],
    },
  ];

所以在我的购物车中,我只有 ID,我想获取食物的对象(项目和配料),请问我该怎么做?

【问题讨论】:

标签: angular typescript


【解决方案1】:

您的购物车中有一组MenuSelection 对象。

要从每个MenuSelection获取产品和成分,您可以尝试以下方法。

你没有提到你想如何存储结果,所以我只是在屏幕上显示它们。您可以根据需要将它们插入到数组或对象中。

var products = [
    {
        id: 0, name: 'Salami', price: 8, hour: null,
        supp:[
          { id: 1123, name: 'fromage', price: 5, hour: null },
          { id: 11234, name: 'bbq', price: 10, hour: null },
        ]
    },
    {
        id: 1, name: 'Fish', price: 10, hour: null,
        supp:[
          { id: 1123, name: 'fromage', price: 5, hour: null },
          { id: 11234, name: 'bbq', price: 10, hour: null },
        ]
    }
  ];

var shoppingCart = [{
  id: 0,
  supp: [1123],
},
{
  id: 1,
  supp: [1123, 11234],
}];

shoppingCart.forEach(menuSelection => {
  let product = products.find(item => item.id === menuSelection.id);
  let foodItem = product.name;
  let ingredients = [];
  
  menuSelection.supp.forEach(suppId => {
    ingredients.push(product.supp.find(item => item.id === suppId));
  });
   
  console.log("Food Item: " + foodItem);
   
  console.log("Ingredients: ");
  ingredients.forEach(item => {
    console.log(item);
  });
});

【讨论】:

    【解决方案2】:

    那么,您有一个id 并在products 数组中寻找相关产品?应该是这样的

    findProductById = (id: number) => this.products.find(product => product.id === id);
    

    【讨论】:

    • 是的,在 products 数组和 products 数组的 supp 数组中,但这不起作用。
    【解决方案3】:

    在此从菜单中获取产品您可以使用

    findProductById = (id: number) => this.products.filter(product => product.id === id);
    

    如果你也想看看它的成分,那么

    findProductById = (id: number) => {
       this.products.filter(
          product => 
          product.id === id || 
          product.supp.filter(ingredients => ingredients.id === id).length
       );
    }
    

    product.supp.filter(ingredients => ingredients.id === id).length 这将返回长度,如果长度为 0,则未找到匹配项,则为 false,否则如果找到匹配项,则长度大于 0。

    如果此条件(product.id === id) 为真,则在顶层找到产品。

    【讨论】:

      猜你喜欢
      • 2020-12-25
      • 1970-01-01
      • 1970-01-01
      • 2011-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-22
      • 1970-01-01
      相关资源
      最近更新 更多