You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何合并MongoDB查询的购物车对象与session中的购物车对象?

How to merge two JavaScript cart objects into one?

My Scenario

I'm fetching a grocery cart from a MongoDB collection with this code, assigning the result to obj and logging it:

const cart = await db.grocerylst.findOne({ userId: req.session.custid }); 
var obj = {}; 
obj = cart.cart; 
console.log(obj);

The obj I get back looks like this:

{ 
  '11f3eba8c2168a485ceba687d7c07571bb7633b8': { 
    productId: 5e2a85b6d052e12078d40418, 
    title: 'JOHNNIE WALKER® PLATINUM LABEL™ 18 YEAR OLD', 
    quantity: 10, 
    totalItemPrice: 37980, 
    options: {}, 
    productImage: '/uploads/5e2a85b6d052e12078d40418/01-johnnie-walker-platinum-18-year-old.png', 
    productComment: null, 
    productSubscription: null, 
    productFrom: { _id: '5e2a4e78d38f491d0082b949', storeName: 'Tiongsan Supermarket', storeLocation: 'Baguio City' }, 
    link: 'Johnywalkerplatinum' 
  }, 
  '204dd16ce5682cc517423ec56d086ef8f56d09b0': { 
    productId: 5e5e0e371c03c01af4ae06de, 
    title: 'Nutella 3kg Bucket', 
    quantity: 2, 
    totalItemPrice: 3100, 
    options: {}, 
    productImage: '/uploads/5e5e0e371c03c01af4ae06de/1546613761-imageService.jpg', 
    productComment: null, 
    productSubscription: null, 
    productFrom: { _id: '5e2a4e78d38f491d0082b949', storeName: 'Tiongsan Supermarket', storeLocation: 'Baguio City' }, 
    link: 'Nutella_3kg_Bucket' 
  } 
}

Meanwhile, req.session.cart contains this separate item:

{ 
  '770d832f5d33e5381790a0393388ac150148bfd6': { 
    productId: 5e5e0d991c03c01af4ae06dd, 
    title: 'Nutella Hazelnut Spread with Cocoa 900g', 
    quantity: 1, 
    totalItemPrice: 455, 
    options: {}, 
    productImage: '/uploads/5e5e0d991c03c01af4ae06dd/nutella.jpg', 
    productComment: null, 
    productSubscription: undefined, 
    productFrom: { _id: '5e2a639744360f00dca93a9d', storeName: 'SM Supermarket', storeLocation: 'Baguio City' }, 
    link: 'Nutella_Hazelnut_Spread_with_Cocoa_900g' 
  } 
}

I need to combine these two objects into one that includes all three items. What's the best way to do this?


Answers

Here are a few simple, reliable ways to merge your two cart objects in JavaScript:

1. Spread Operator (Modern & Concise)

The spread operator (...) is my go-to for this kind of task. It creates a brand new object by "spreading" all properties from both source objects into it. Since all your keys are unique here, every item will be included without overwrites. If there were duplicate keys later, the second object (req.session.cart) would take precedence:

const mergedCart = { ...obj, ...req.session.cart };
console.log(mergedCart);

2. Object.assign() (More Compatible)

If you need to support older JavaScript environments that don't have the spread operator, Object.assign() works great. It copies all enumerable properties from the source objects into a target object (we use an empty object as the target to avoid modifying the original obj):

const mergedCart = Object.assign({}, obj, req.session.cart);
console.log(mergedCart);

3. Manual Loop (For Custom Logic)

If you ever need to add custom behavior—like merging nested product details instead of overwriting them, or handling duplicate keys in a specific way—you can loop through the properties manually:

// Start with a copy of the first cart to avoid modifying the original
const mergedCart = { ...obj };

// Loop through each item in the session cart
for (const itemKey in req.session.cart) {
  if (req.session.cart.hasOwnProperty(itemKey)) {
    // Add your custom logic here if needed
    mergedCart[itemKey] = req.session.cart[itemKey];
  }
}

console.log(mergedCart);

Quick Note

Since all the item keys in your two objects are unique, all three products will show up in the merged cart no matter which method you use. If you ever end up with duplicate keys down the line, just remember that the later object in the merge will overwrite the earlier one's value for that key.


内容的提问来源于stack exchange,提问作者sonjasan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 11:52:33