JavaScript中合并数组对象并归集postedUserId的问题求助
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 inarr1, building up our final merged array (accumulator).find(): Checks if we already have an entry in the accumulator with the sameid(you can adjust this condition if you need to match multiple fields, likename,lname, anduserIdtogether).- Spread Operator (
...currentItem): Copies all existing properties from the current object into the new entry, so we don't have to manually setname,lname, etc. postedUsersArray: For new entries, we initialize this array with the currentpostedUserId; for existing entries, we just push the newpostedUserIdinto 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

