简体   繁体   English

如何检查我推入对象的对象数组是否具有来自另一个对象数组的特定键值

[英]How to check if an array of objects where I push into objects has a specific key value from another array of objects

This is what I have so far and what I've and tried:这是我到目前为止所拥有的以及我已经尝试过的:

groceryList = [];

ngOnInit() {
  this._recipesSub = this.recipesService.recipes.subscribe((receivedData) => {
    this.loadedRecipes = receivedData.recipes;
  });
}
onCheckRecipe(e) {
    if (e.detail.checked === true) {
      let tickedRecipe = e.detail.value;
      let selectedRecipeIngredients;
      for (let recipe of this.loadedRecipes) {
        if (recipe.name === tickedRecipe) {
          selectedRecipeIngredients = recipe.ingredients;
        }
      }
      for (let selectedIng of selectedRecipeIngredients) {
        for (let existingIng of this.groceryList) {
          if (selectedIng.name) {
            this.groceryList.push(selectedIng);
          }
        }
      }
      console.log(this.groceryList);
    }
  }

This is what I receive in my console:这是我在控制台中收到的内容:

(8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {_id: "5f64ac1eb227fea1f63a5c99", name: "chia seeds", quantity: "10g"}
1: {_id: "5f64ac1eb227fea1f63a5c9a", name: "cherries", quantity: "15g"}
2: {_id: "5f64ac1eb227fea1f63a5c9b", name: "honey", quantity: "30g"}
3: {_id: "5f64ac1eb227fea1f63a5c9c", name: "almond flour", quantity: "10g"}
4: {_id: "5f64ac1eb227fea1f63a5c9e", name: "almond flour", quantity: "10g"}
5: {_id: "5f64ac1eb227fea1f63a5c9f", name: "egg", quantity: "10g"}
6: {_id: "5f64ac1eb227fea1f63a5ca0", name: "unsalted butter", quantity: "30g"}
7: {_id: "5f64ac1eb227fea1f63a5ca1", name: "peanut butter", quantity: "50g"}
length: 8
__proto__: Array(0)

and my desire outcome is not to have name: "almond flour" twice because it was already in the array, so i can be able to add just the object that which name value doesn't exist already:并且我想要的结果不是name: "almond flour"两次,因为它已经在数组中,所以我可以只添加名称值不存在的对象:

Instead of 3: {_id: "5f64ac1eb227fea1f63a5c9c", name: "almond flour", quantity: "10g"}, {_id: "5f64ac1eb227fea1f63a5c9e", name: "almond flour", quantity: "10g"} to be {_id: "5f64ac1eb227fea1f63a5c9e", name: "almond flour", quantity: "20g"}相反的3: {_id: "5f64ac1eb227fea1f63a5c9c", name: "almond flour", quantity: "10g"}, {_id: "5f64ac1eb227fea1f63a5c9e", name: "almond flour", quantity: "10g"}{_id: "5f64ac1eb227fea1f63a5c9e", name: "almond flour", quantity: "20g"}

What I want to achieve is to add to my groceryList array each Ingredient only if that ingredient is not present already and if it's present to add just the quantity of that ingredient to an existing key.我想要实现的是将每个成分添加到我的groceryList数组中,仅当该成分不存在并且存在时才将该成分的数量添加到现有键中。 For example if i have the ingredient {_id: "5f64ac1eb227fea1f63a5c99", name: "chia seeds", quantity: "10g"} to add just the quantity and not to create a new obj of ingredient in my groceryList例如,如果我有成分{_id: "5f64ac1eb227fea1f63a5c99", name: "chia seeds", quantity: "10g"}只添加数量而不是在我的groceryList创建一个新的成分groceryList

I am don't know what approach to take.. If you guys have any idea I would really appreciate it.我不知道采取什么方法.. 如果你们有任何想法,我将不胜感激。

** Also the remove option ** 还有删除选项

onCheckRecipe(e) {
    if (e.detail.checked === true) {
      for (let recipe of this.loadedRecipes) {
        if (recipe.name === e.detail.value) {
          recipe.ingredients.forEach((eachIngredient) => {
            let matchedIng = this.groceryList.find(function (foundIng) {
              return foundIng.name === eachIngredient.name;
            });
            if (matchedIng) {
              matchedIng.quantity =
                matchedIng.quantity + eachIngredient.quantity;
            } else {
              this.groceryList.push(eachIngredient);
            }
          });
        }
      }
    } else {
      for (let recipe of this.loadedRecipes) {
        if (recipe.name === e.detail.value) {
          recipe.ingredients.forEach((element) => {
            let matched = this.groceryList.find(function (foundIngre) {
              return foundIngre.name === element.name;
            });
            if (matched.quantity === element.quantity) {
              let index = this.groceryList.findIndex(
                (x) => x.name === matched.name
              );
              this.groceryList.splice(index, 1);
            } else {
              matched.quantity = matched.quantity - element.quantity;
            }
          });
        }
      }
    }
  }

Loop over the ingredients array and use Array.prototype.find() to look for a match for each iteration.循环遍历成分数组并使用Array.prototype.find()查找每次迭代的匹配项。 If one exists, update quantity, otherwise push ingredient object to the array如果存在,则更新数量,否则将成分对象推入数组

One suggestion to simplify the computation would be add another field for the units and store quantity as a number so you don't need to parse units from a string just to do the simple math简化计算的一个建议是为单位添加另一个字段并将数量存储为数字,这样您就不需要为了做简单的数学运算而从字符串中解析单位

 const ingredients = [{_id: "5f64ac1eb227fea1f63a5c9e", name: "almond flour", quantity: "10g"}]; ingredients.forEach(ingr => { // returns matching object or undefined const wanted = data.find(({_id}) => _id === ingr._id); if(wanted){ const {quantity: wq} = wanted, units = wq.match(/\\D+/)[0]; wanted.quantity = parseInt(wq) + parseInt(ingr.quantity) + units; }else{ data.push(obj) } }) console.log(data)
 .as-console-wrapper {max-height: 100%!important;top:0;}
 <script> const data = [{_id: "5f64ac1eb227fea1f63a5c99", name: "chia seeds", quantity: "10g"}, {_id: "5f64ac1eb227fea1f63a5c9a", name: "cherries", quantity: "15g"}, {_id: "5f64ac1eb227fea1f63a5c9b", name: "honey", quantity: "30g"}, {_id: "5f64ac1eb227fea1f63a5c9e", name: "almond flour", quantity: "10g"}, {_id: "5f64ac1eb227fea1f63a5c9f", name: "egg", quantity: "10g"}, {_id: "5f64ac1eb227fea1f63a5ca0", name: "unsalted butter", quantity: "30g"}, {_id: "5f64ac1eb227fea1f63a5ca1", name: "peanut butter", quantity: "50g"}] </script>

This is my Solution, i hope that is helpful :这是我的解决方案,希望对您有所帮助:

const data = [
  { _id: "5f64ac1eb227fea1f63a5c99", name: "chia seeds", quantity: "10g" },
  { _id: "sdf7687hkksjj8881zzaooPP", name: "peanut butter", quantity: "20g" },
  { _id: "abcf781eb227fea1f63a5c9a", name: "cherries", quantity: "15g" },
  { _id: "5f64ac1eb227fea1f63a5c9b", name: "honey", quantity: "30g" },
  { _id: "5f64ac1eb227fea1f63a5c9c", name: "almond flour", quantity: "10g" },
  { _id: "5f64ac1eb227fea1f63a5c9e", name: "almond flour", quantity: "10g" },
  { _id: "5f64ac1eb227fea1f63a5c9f", name: "egg", quantity: "10g" },
  { _id: "ghg990c1eb227fea1f63a5c7", name: "egg", quantity: "19g" },
  { _id: "dsfsdffer340fea1f63a5ca0", name: "unsalted butter", quantity: "30g" },
  { _id: "5f64ac1eb227fea1f63a5ca1", name: "peanut butter", quantity: "50g" }
];

const groceryList = data.reduce(
  (acc, value) => {
    const index = acc.findIndex(elt => elt.name === value.name);
    if (index !== -1) {
      const accQuantity = acc[index].quantity;
      const valueQuantity = value.quantity;
      const unit = accQuantity.match(/\D+/)[0];
      acc[index].quantity = +accQuantity.match(/\d+/)[0] + +valueQuantity.match(/\d+/)[0] + unit;
    } else {
      acc.push(value);
    }
    return acc;
  }, []
);
console.log(groceryList);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 检查数组或对象是否具有特定键 - Check if an array or objects has a specific key 如何从 state 获取对象数组并将对象的特定值推送到新数组中 - How do I take an array of objects from state and push a specific value of the objects into a new array 如何检查对象数组是否具有相同键的相同值? - How to check if array of objects has same value for same key? 如何检查对象数组是否包含特定键的相同值 - How to check if the array of objects contains same value for a specific key 如何获取键值具有特定字符的对象数组中的最后一项? - How to get the last item in an array of objects where the value to a key has a specific character? 如何将键/值对从 for 循环推送到现有的对象数组 - How to push key/value pairs from for loop to existing array of objects 将数组中的对象推入另一个数组的特定字段 - Push objects from array into specific fields of another array 如何在对象内的对象数组中检索特定键值? - How to retrieve specific key value in an array of objects within objects? 将对象数组按其值推送到另一个数组 - Push an array of objects by it's value to another array 如何从具有特定键值的对象数组中获取 object? - How to get an object from an array of objects with a specific value for a key?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM