简体   繁体   English

检查还包含嵌套的 arrays 和对象的对象数组是否相同,如果是,则将它们合并为一个 object 并将键添加到一起

[英]Check if array of objects, which also contain nested arrays with objects, are the same, if so, combine them into one object and add the keys together

I would need to check if the objects in the "food" array are equal to each other, and the ones that are - combine into one adding amount and mody.amount and leaving the rest unchanged.我需要检查“食物”数组中的对象是否彼此相等,以及那些 - 组合成一个添加量和 mody.amount 并保持 rest 不变。 This is just for better order data displaying.这只是为了更好地显示订单数据。 I tried with lodash library and reduce but but I don't know exactly how to construct this function that nested objects(mody) adds values as well, and in case isEqual returns false keep the object while concurrently concatenating the identical ones.我尝试使用 lodash 库和 reduce,但我不知道如何构造这个嵌套对象(mody)也添加值的 function,如果 isEqual 返回 false,请保留 object,同时连接相同的对象。

What I tried:我尝试了什么:

obj1.reduce((prev, next) => _.isEqual(prev, next) ? {...prev, amount: prev.amount + next.amount} : next

Now it looks like that:现在看起来像这样:

 const food =  [
    {
        "id": 1,
        "name": "chicken",
        "price": 6,
        "amount": 1,
        "mody": [
            {
                "id": 33,
                "name": "cheese",
                "price": 1,
                "amount": 1
            },
            {
                "id": 34,
                "name": "chips",
                "price": 2,
                "amount": 1
            }
        ]
    },
    {
        "id": 1,
        "name": "chicken",
        "price": 6,
        "amount": 1,
        "mody": [
            {
                "id": 33,
                "name": "cheese",
                "price": 1,
                "amount": 1
            },
            {
                "id": 34,
                "name": "chips",
                "price": 2,
                "amount": 1
            }
        ]
    },
    {
        "id": 2,
        "name": "pizza",
        "price": 6,
        "amount": 2,
        "mody": [
            {
                "id": 12,
                "name": "extra cheese",
                "price": 2,
                "amount": 1
            }
        ]
    }
]
  

and would need something like that:并且需要这样的东西:

const food = [
    {
        "id": 1,
        "name": "chicken",
        "price": 6,
        "amount": 2,
        "mody": [
            {
                "id": 33,
                "name": "cheese",
                "price": 1,
                "amount": 2
            },
            {
                "id": 34,
                "name": "chips",
                "price": 2,
                "amount": 2
            }
        ]
    },
    {
        "id": 2,
        "name": "pizza",
        "price": 6,
        "amount": 2,
        "mody": [
            {
                "id": 12,
                "name": "extra cheese",
                "price": 2,
                "amount": 1
            }
        ]
    }
]
  

The algorithm to sum the food amounts and mody amounts are almost the same, the difference is that for each food that has the same id we will sum the mody amount.对食物量和mod量求和的算法几乎相同,不同之处在于对于具有相同id的每种食物,我们将求和mody量。 To make the algorithm simpler I used a dictionary as the accumulator on the reduce function so we have a unique element per key.为了使算法更简单,我使用字典作为reduce function 的累加器,因此每个键都有一个唯一元素。 This element will be our final food or mody with the amount sum.这个元素将是我们最后的食物或食物与金额的总和。

Mody sum algoritm:么和算法:

const sumMody = (modyAccumulator, currentMody) => {
  //Get the stored mody in the accumulator dictionary or null if it the mody is not stored
  const storedMody = modyAccumulator[currentMody.id] ?? null 
  
  // if mody is null then add mody to the dictionary using its id as key
  if (!storedMody) {
    modyAccumulator[currentMody.id] = currentMody
  } else {
    //Mody is stored then sum amount
    storedMody.amount += currentMody.amount
  }

  return modyAccumulator
}

The food sum algoritm is the same as the sumMody , the only difference is that it calls the sumMody function when the foods are equal:食物总和算法与sumMody相同,唯一的区别是当食物相等时它调用sumMody function:

const sumFood = (foodAccumulator, currentFood) => {
  //Get the stored foodin the accumulator dictionary or null if it the food is not stored
  const storedFood = foodAccumulator[currentFood.id] ?? null

  // if food is null then add food to the dictionary using its id as key
  if (!storedFood) {
    foodAccumulator[currentFood.id] = currentFood
  } else {
    //Food is stored then sum food amount
    storedFood.amount += currentFood.amount

    //Create a list with mody from both foods
    const modyList = [...storedFood.mody, ...currentFood.mody]

    //Use reduce passing the sumMody callback function and initialize the accumulator with a dictionary
    const modySumDictionary = modyList.reduce(sumMody, {})

    /* The function above return a dictionary where the identifier is the mody.id 
      and the value is the mody. We only need the values from that dictionary so 
      we use Object.values to extract all the values. */
    storedFood.mody = Object.values(modySumDictionary)
  }

  return foodAccumulator
}

To execute both sums:要执行两个总和:

//As explained before the reduce function will return a dictionary so we use Object.values to get only the values
const result = Object.values(food.reduce(sumFood, {}))

console.log(result)

Algoritm without comments:没有评论的算法:

const sumMody = (modyAccumulator, currentMody) => {
  const storedMody = modyAccumulator[currentMody.id] ?? null
  if (!storedMody) {
    modyAccumulator[currentMody.id] = currentMody
  } else {
    storedMody.amount += currentMody.amount
  }

  return modyAccumulator
}

const sumFood = (foodAccumulator, currentFood) => {
  const storedFood = foodAccumulator[currentFood.id] ?? null
  if (!storedFood) {
    foodAccumulator[currentFood.id] = currentFood
  } else {
    storedFood.amount += currentFood.amount

    const modyList = [...storedFood.mody, ...currentFood.mody]

    const modySumDictionary  = modyList.reduce(sumMody, {})
    storedFood.mody = Object.values(modySumDictionary)
  }

  return foodAccumulator
}

const result = Object.values(food.reduce(sumFood, {}))

console.log(result)

Reference to Object.values参考Object.values

暂无
暂无

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

相关问题 如何将具有相同键的对象数组合到一个对象中? - How can I combine an array of objects with the same keys into one object? 如何合并包含相同对象键的多个子数组? - how to combine multiple sub-arrays that contain same objects' keys? 检查对象数组中的任何键是否包含来自数组数组对象的值的最佳方法是什么? - What would be the best way to check if any of the keys in an array of objects contain a value from an object of arrays array? 访问对象中的嵌套键并将它们与其他对象键进行比较,但第二个是对象数组 - Accessing nested keys in object and compare them to other object keys, but the 2nd one is an array of objects 我有一组对象,如果其中一个键匹配(不覆盖初始属性),我想将它们组合成一个 object - I have an array of objects and want to combine them into one object IF the one of the keys match (without overwriting the initial properties) 包含对象数组的嵌套ng-repeat包含数组 - Nested ng-repeat with array of objects which contain arrays 如何将动态对象添加到嵌套数组中,使其包含相似的结构 - How to add dynamic objects into the nested array so that it will contain similar structure 对象数组:从 object 中删除键并将它们作为新的 object 添加到同一数组中 - Array of objects: delete keys from object and add them as a new object to the same array 通过 2 个不同的键比较对象的 2 个 arrays。 并制作一个包含父母和孩子的嵌套 object - Compare 2 arrays of objects by 2 different keys. And make one nested object which contains parent and child 合并两个对象数组并组合在相同的键上 - Merge Two Arrays of Objects and combine on same keys
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM