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

JavaScript中合并数组对象并归集postedUserId的问题求助

Fixing Array Object Merging in JavaScript

Hey Karan, let's tackle that array merging problem you're working on. You want to combine objects that share the same core fields (like name, lname, userId, id) and collect all unique postedUserId values into a new postedUsers array—here's a clean, efficient way to do it:

Step-by-Step Solution

First, let's start with your original array:

var arr1 = [
  { "name": "harkaran", "lname": "sofat", "userId": 49, "postedUserId": 52, "id": 21 },
  { "name": "harkaran", "lname": "sofat", "userId": 49, "postedUserId": 57, "id": 21 }
];

We'll use JavaScript's reduce() method to group and merge the objects. This method is perfect for accumulating array values into a single structure (in this case, our merged array):

const mergedArr = arr1.reduce((accumulator, currentItem) => {
  // Look for an existing item in the accumulator that matches the core fields
  const existingEntry = accumulator.find(entry => entry.id === currentItem.id);

  if (existingEntry) {
    // If we found a match, add the current postedUserId to its postedUsers array
    existingEntry.postedUsers.push(currentItem.postedUserId);
  } else {
    // If no match exists, create a new object with all current fields + the postedUsers array
    accumulator.push({
      ...currentItem,
      postedUsers: [currentItem.postedUserId]
    });
  }

  return accumulator;
}, []); // Start with an empty array as the initial accumulator

console.log(mergedArr);

What This Does

  • reduce(): Iterates over each object in arr1, building up our final merged array (accumulator).
  • find(): Checks if we already have an entry in the accumulator with the same id (you can adjust this condition if you need to match multiple fields, like name, lname, and userId together).
  • Spread Operator (...currentItem): Copies all existing properties from the current object into the new entry, so we don't have to manually set name, lname, etc.
  • postedUsers Array: For new entries, we initialize this array with the current postedUserId; for existing entries, we just push the new postedUserId into the array.

If You Need Strict Matching

If you want to ensure objects are merged only when all core fields match (not just id), update the find() condition like this:

const existingEntry = accumulator.find(entry => 
  entry.name === currentItem.name &&
  entry.lname === currentItem.lname &&
  entry.userId === currentItem.userId &&
  entry.id === currentItem.id
);

Result

Running the code will give you exactly the output you want:

[
  { 
    "name": "harkaran", 
    "lname": "sofat", 
    "userId": 49, 
    "postedUserId": 52, 
    "id": 21, 
    "postedUsers": [52, 57] 
  }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:07:00