【问题标题】:Javascript obtain Shopping List from arrayJavascript 从数组中获取购物清单
【发布时间】:2020-09-13 20:32:48
【问题描述】:

我是 javascript 新手,所以我什至不知道从哪里开始。请有人帮助我。

我有这个成分清单:

const Ingris = [
  {
    val: "onion,",
    amount: "1",
  },
  {
    val: "paprika",
    amount: "½ tsp",
  },
  {
    val: "yogurt",
    amount: "1/2 Cup",
  },
  {
    val: "fine sea salt",
    amount: "½ tsp  ",
  },
];

我想根据以下这些变量对它们进行分类:

var spices = ["paprika", "parsley", "peppermint", "poppy seed", "rosemary"];
var meats = ["steak", "ground beef", "stewing beef", "roast beef", "ribs"];
var dairy = ["milk", "eggs", "cheese", "yogurt"];
var produce = ["peppers", "radishes", "onions", "tomatoes"];

这是我想要获得的:

// desired output:

const ShoppingList = [
  {
    produceOutput: [
      {
        val: "garlic, minced",
        amount: "8 cloves ",
      },
    ],
    spicesOutput: [
      {
        val: "paprika",
        amount: "½ tsp  ",
      },
      {
        val: "onion",
        amount: "1",
      },
    ],
    NoCategoryOutput: [
      {
        val: "fine sea salt",
        amount: "½ tsp",
      },
    ],
  },
];

【问题讨论】:

标签: javascript arrays sorting object javascript-objects


【解决方案1】:

正如这里的其他人建议使用现代的reduceincludesforEach 数组方法...以防万一您需要支持较旧的浏览器,或者只是更“经典”的实现,您可以使用一个简单的for 循环使用 indexOf 数组方法。

const Ingris = [{ val: "onion,", amount: "1", },
  { val: "paprika", amount: "½ tsp",  },
  { val: "yogurt", amount: "1/2 Cup", },
  { val: "fine sea salt", amount: "½ tsp  ", },
];
var spices = ["paprika", "parsley", "peppermint", "poppy seed", "rosemary"];
var meats = ["steak", "ground beef", "stewing beef", "roast beef", "ribs"];
var dairy = ["milk", "eggs", "cheese", "yogurt"];
var produce = ["peppers", "radishes", "onions", "tomatoes"];

ShoppingList = {
  produceOutput: [],
  spicesOutput: [],
  meatsOutput: [],
  dairyOutput: [],
  NoCategoryOutput: [],
};

for (var i = 0; i < Ingris.length; i++) {
  var ingredient = Ingris[i];
  if (spices.indexOf(ingredient.val) >= 0) {
    ShoppingList.spicesOutput.push(ingredient);
  } else if (meats.indexOf(ingredient.val) >= 0) {
    ShoppingList.meatsOutput.push(ingredient);
  } else if (dairy.indexOf(ingredient.val) >= 0) {
    ShoppingList.dairyOutput.push(ingredient);
  } else if (produce.indexOf(ingredient.val) >= 0) {
    ShoppingList.produceOutput.push(ingredient);
  } else {
    ShoppingList.NoCategoryOutput.push(ingredient);
  }
}

console.log(ShoppingList)

另外请注意,如果 Ingris 中有一些重复的成分 - 他们不会总结它们的数量。为此,您需要以某种数字格式(例如十进制数)提供或转换每个金额。此外,除了简单的push,还有一些额外的逻辑检查当前成分是否已经在列表中,如果是,则添加它们的数量。

【讨论】:

  • 非常感谢您的回答,但它给出了一个错误
  • @DilhanBhagat 你只需要添加你的数组
【解决方案2】:

您可以使用基本的reducer 进行此类操作。

const categorizedOutput = Ingris.reduce((acc, cur) => {
  if (spices.includes(cur.val)) {
    acc.spices.push(cur);
  } else if (meats.includes(cur.val)) {
    acc.meats.push(cur);
  } else if (dairy.includes(cur.val)) {
    acc.dairy.push(cur);
  } else if (produce.includes(cur.val)) {
    acc.produce.push(cur);
  } else {
    acc.other.push(cur);
  }
  return acc;
}, {
  spices: [],
  meats: [],
  dairy: [],
  produce: [],
  other: []
})

【讨论】:

    【解决方案3】:

    var spices  = ["paprika", "parsley", "peppermint", "poppy seed", "rosemary"];
    var meats   = ["steak", "ground beef", "stewing beef", "roast beef", "ribs"];
    var dairy   = ["milk", "eggs", "cheese", "yogurt"];
    var produce = ["peppers", "radishes", "onions", "tomatoes"];
    
    var ingredients=[
      {"val":"onion,"       , "amount":"1"},
      {"val":"paprika"      , "amount":"½ tsp"},
      {"val":"yogurt"       , "amount":"1/2 Cup"},
      {"val":"fine sea salt", "amount":"½ tsp"}
    ];
    
    var shoppingList={spices:[], meats:[], dairy:[], produce:[], other:[]};
    
    ingredients.forEach(ingredient=>{
      if(spices.includes(ingredient.val)) shoppingList.spices.push(ingredient);
      else if(meats.includes(ingredient.val)) shoppingList.meats.push(ingredient);
      else if(dairy.includes(ingredient.val)) shoppingList.dairy.push(ingredient);
      else if(produce.includes(ingredient.val)) shoppingList.produce.push(ingredient);
      else shoppingList.other.push(ingredient);
    });
    
    console.log(shoppingList);

    【讨论】:

      【解决方案4】:

      这是一种稍微参数化的方法。我将不同的食物类别组合成一个对象cat 并允许部分匹配成分(单数匹配复数):

      const cat={ 
        spices: ["paprika", "parsley", "peppermint", "poppy seed", "rosemary","fine sea salt"],
        meats: ["steak", "ground beef", "stewing beef", "roast beef", "ribs"],
        dairy: ["milk", "eggs", "cheese", "yogurt"],
        produce: ["peppers", "radishes", "onions", "tomatoes"]};
      
      var ingredients=[
        {"val":"onion"       , "amount":"1"},
        {"val":"paprika"      , "amount":"½ tsp"},
        {"val":"yogurt"       , "amount":"1/2 Cup"},
        {"val":"fine sea salt", "amount":"½ tsp"}
      ];
      
      const shop=ingredients.reduce((acc,ing)=>{
        Object.entries(cat).some(([ca,pr])=>
          pr.find(p=>p.indexOf(ing.val)>-1) && 
          (acc[ca]=acc[ca]||[]).push(ing) )
        || (acc.other=acc.other||[]).push(ing);
        return acc;
      }, {});
      console.log(shop);

      【讨论】:

        猜你喜欢
        • 2020-08-06
        • 2018-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多