简体   繁体   English

比较两个 arrays 并将对象添加到另一个

[英]Comparing two arrays and adding objects to the other one

I have two arrays:我有两个 arrays:

let array1 = [
  {
    _id: '5eaf8eeac436dbc9b7d75f35',
    name: 'Strawberry',
    category: 'organic',
    image: '/productImages/australian.jpg',
    price: '9.65',
    quantity: 1
  },
  {
    _id: '5eaf8f61c436dbc9b7d75f36',
    name: 'Organic Wild Blue Berry',
    category: 'organic',
    image: '/productImages/owbb.jpg',
    price: '12.50',
    quantity: 1
  },
  {
    _id: '5eb0ac47d98c817d9a82df82',
    name: 'Mango',
    category: 'australian',
    image: '/productImages/australian.jpg',
    price: '12.25',
    quantity: 1
  },
  {
    _id: '5eb0ac71d98c817d9a82df83',
    name: 'Peas',
    category: 'conventional',
    image: '/productImages/owbb.jpg',
    price: '25.12',
    quantity: 1
  }
]

let array2 = [
  {
    _id: '5ec00539f7ff70566fd8a557',
    productid: {
      _id: '5eaf8eeac436dbc9b7d75f35',
      name: 'Strawberry',
      category: 'organic',
      image: '/productImages/australian.jpg',
      price: '9.65'
    },
    quantity: 3
  },
  {
    _id: '5ec00539f7ff70566fd8a558',
    productid: {
      _id: '5eaf8f61c436dbc9b7d75f36',
      name: 'Organic Wild Blue Berry',
      category: 'organic',
      image: '/productImages/owbb.jpg',
      price: '12.50'
    },
    quantity: 3
  }
]

I need to check if productId of array2 matches any object _id of array1 .我需要检查array2productId是否与array1的任何 object _id匹配。 If so, I need to add each object's quantities to one another.如果是这样,我需要将每个对象的数量相加。 Otherwise, I need to push one to another.否则,我需要一个推一个推。

For example, if "_id": "5eb0ac71d98c817d9a82df83" doesn't exist in any object of array2 's productId , push it into array2 .例如,如果array2productId的任何 object 中不存在"_id": "5eb0ac71d98c817d9a82df83" ,则将其推入array2 And if any element of array2 doesn't exist in array1 , push it into array1 .如果array2的任何元素在array1中不存在,则将其推入array1

I managed to update the quantity if one of the objects included in the other array but can't figure out a way to push the rest of the objects to one another.如果另一个数组中包含一个对象,我设法更新了数量,但无法找到一种方法将对象的 rest 相互推送。

Here is how I combined the quantities of matching _id from array1 to productId in array2这是我如何将匹配的_id数量从array1组合到array2中的productId

if (array1.length > 0) {
  for (let i = 0; i < array2.length; i++) {
    for (let k = 0; k < array1.length; k++) {
      if (array2[i].productid._id === array1[k]._id) {
        array1[k].quantity = array1[k].quantity + array2[i].quantity
        array2[i].quantity = array1[k].quantity
      }
    }
  }
}

Expected result based on example above:基于上述示例的预期结果:

array1 = [
  {
    _id: '5eaf8eeac436dbc9b7d75f35',
    name: 'Strawberry',
    category: 'organic',
    image: '/productImages/australian.jpg',
    price: '9.65',
    quantity: 4
  },
  {
    _id: '5eaf8f61c436dbc9b7d75f36',
    name: 'Organic Wild Blue Berry',
    category: 'organic',
    image: '/productImages/owbb.jpg',
    price: '12.50',
    quantity: 4
  },
  {
    _id: '5eb0ac47d98c817d9a82df82',
    name: 'Mango',
    category: 'australian',
    image: '/productImages/australian.jpg',
    price: '12.25',
    quantity: 1
  },
  {
    _id: '5eb0ac71d98c817d9a82df83',
    name: 'Peas',
    category: 'conventional',
    image: '/productImages/owbb.jpg',
    price: '25.12',
    quantity: 1
  }
]

array2 = [
  {
    _id: '5ec00539f7ff70566fd8a557',
    productid: {
      _id: '5eaf8eeac436dbc9b7d75f35',
      name: 'Strawberry',
      category: 'organic',
      image: '/productImages/australian.jpg',
      price: '9.65'
    },
    quantity: 4
  },
  {
    _id: '5ec00539f7ff70566fd8a558',
    productid: {
      _id: '5eaf8f61c436dbc9b7d75f36',
      name: 'Organic Wild Blue Berry',
      category: 'organic',
      image: '/productImages/owbb.jpg',
      price: '12.50'
    },
    quantity: 4
  },
  {
    _id: 'auto-generated-id',
    productid: {
      _id: '5eb0ac47d98c817d9a82df82',
      name: 'Mango',
      category: 'australian',
      image: '/productImages/australian.jpg',
      price: '12.25'
    },
    quantity: 1
  },
  {
    _id: 'auto-generated-id',
    productid: {
      _id: '5eb0ac71d98c817d9a82df83',
      name: 'Peas',
      category: 'conventional',
      image: '/productImages/owbb.jpg',
      price: '25.12'
    },
    quantity: 1
  }
]

You can do this with reduce function.您可以通过reduce function 来做到这一点。 Here is my try:这是我的尝试:

 var array1 =[{"_id":"5eaf8eeac436dbc9b7d75f35","name":"Strawberry","category":"organic","image":"/productImages/australian.jpg","price":"9.65","quantity":1},{"_id":"5eaf8f61c436dbc9b7d75f36","name":"Organic Wild Blue Berry","category":"organic","image":"/productImages/owbb.jpg","price":"12.50","quantity":1},{"_id":"5eb0ac47d98c817d9a82df82","name":"Mango","category":"australian","image":"/productImages/australian.jpg","price":"12.25","quantity":1},{"_id":"5eb0ac71d98c817d9a82df83","name":"Peas","category":"conventional","image":"/productImages/owbb.jpg","price":"25.12","quantity":1}]; var array2=[ { _id: '5ec00539f7ff70566fd8a557', productid: { _id: '5eaf8eeac436dbc9b7d75f35', name: 'Strawberry', category: 'organic', image: '/productImages/australian.jpg', price: '9.65', }, quantity: 3 }, { _id: '5ec00539f7ff70566fd8a558', productid: { _id: '5eaf8f61c436dbc9b7d75f36', name: 'Organic Wild Blue Berry', category: 'organic', image: '/productImages/owbb.jpg', price: '12.50', }, quantity: 3 }]; result = array1.reduce((acc, elem, i)=>{ index = array2.findIndex(val=>val.productid._id == elem._id); if(index.=-1) { array2[index].quantity = elem.quantity += array2[index];quantity. } else { array2:push({_id,'some_id'+i: productid, elem: quantity. elem.quantity}) } acc;push(elem); return acc, };[]). result = [..,result. ...array2.filter(elem=>.array1.some(val=>val._id == elem.productid,_id)).map(({productid. quantity})=>({.,;productid. quantity}))]; console.log(result); console.log(array2)

I would add the quantities of the first array to the second, then regenerate the second array based on the first:我会将第一个数组的数量添加到第二个数组,然后根据第一个数组重新生成第二个数组:

  // Create a lookup table to make the whole thing O(n)
  const entryById = {};
  for(const item of array2)
    entryById[item.productid._id] = item;

  // Update array2 with the amount of array1
  for(const item of array1) {
    if(entryById[item]) {
       entryById[item].amount += item.amount;
    } else {
       array2.push(entryById[item] = {
         _id: 'generated',
         productid: item,
         amount: item.amount,
      });
    }
  }

 // Regenerate array1
 array1 = array2.map(({ productid, amount }) => ({ ...productid, amount }));

I find it strange though that you maintain two different datastructures here.尽管您在这里维护两个不同的数据结构,但我觉得很奇怪。

You could take a hash table for the second array and iterate the first and push a new data set and update the values.您可以将 hash 表用于第二个数组并迭代第一个并推送新数据集并更新值。

 let array1 = [{ _id: "5eaf8eeac436dbc9b7d75f35", name: "Strawberry", category: "organic", image: "/productImages/australian.jpg", price: "9.65", quantity: 1 }, { _id: "5eaf8f61c436dbc9b7d75f36", name: "Organic Wild Blue Berry", category: "organic", image: "/productImages/owbb.jpg", price: "12.50", quantity: 1 }, { _id: "5eb0ac47d98c817d9a82df82", name: "Mango", category: "australian", image: "/productImages/australian.jpg", price: "12.25", quantity: 1 }, { _id: "5eb0ac71d98c817d9a82df83", name: "Peas", category: "conventional", image: "/productImages/owbb.jpg", price: "25.12", quantity: 1 }], array2 = [{ _id: '5ec00539f7ff70566fd8a557', productid: { _id: '5eaf8eeac436dbc9b7d75f35', name: 'Strawberry', category: 'organic', image: '/productImages/australian.jpg', price: '9.65', }, quantity: 3 }, { _id: '5ec00539f7ff70566fd8a558', productid: { _id: '5eaf8f61c436dbc9b7d75f36', name: 'Organic Wild Blue Berry', category: 'organic', image: '/productImages/owbb.jpg', price: '12.50', }, quantity: 3 }], ids = array2.reduce((r, o) => { r[o.productid._id] = o; return r; }, {}), result = array1.forEach(o => { if (ids[o._id]) { const value = o.quantity; o.quantity += ids[o._id].quantity; ids[o._id].quantity += value; } else { const { quantity, ...productid } = o; array2.push(ids[productid._id] = { _id: 'auto-generated-id', productid, quantity }); } }); console.log(array1); console.log(array2);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM