如何将重复的JSON对象合并为单个对象?
Hey there! Let's work through how to merge those duplicate JSON objects you have. First, a quick heads-up: standard JSON doesn't allow duplicate keys in an object (like having two attributeValue entries). Most parsers will just overwrite the first value with the last one, so that approach isn't practical long-term. Instead, we'll merge the differing attributeValue entries into a single, combined value (either an array or a concatenated string) while keeping all shared fields intact.
Step-by-Step Solution (JavaScript Example)
We'll use array reduction to group objects by their attributeId, then merge the attributeValue entries:
// Your original JSON data const originalData = [ { "attributeId": 6, "attributeType": "price", "attributeValue": "{10,20,100}", "displayOn": "true", "attributeName": "price" }, { "attributeId": 6, "attributeType": "price", "attributeName": "price", "displayOn": "true", "attributeValue": "{21,40,200}" } ]; // Merge objects by attributeId and combine attributeValues const mergedData = Object.values(originalData.reduce((accumulator, currentItem) => { const id = currentItem.attributeId; // If we haven't seen this ID before, initialize the merged object if (!accumulator[id]) { accumulator[id] = { ...currentItem, // Start with an array to hold multiple attributeValues attributeValue: [currentItem.attributeValue] }; } else { // Add the new attributeValue to the existing array accumulator[id].attributeValue.push(currentItem.attributeValue); } return accumulator; }, {})).map(mergedItem => { // Optional: Convert the array of values into a single concatenated string // This mimics your original {x,y,z} format but combines all values const combinedValues = mergedItem.attributeValue .map(val => val.slice(1, -1)) // Remove the curly braces from each value .join(','); return { ...mergedItem, attributeValue: `{${combinedValues}}` }; }); // Log the result console.log(JSON.stringify(mergedData, null, 2));
Output
This will give you a clean, valid JSON object with combined values:
[ { "attributeId": 6, "attributeType": "price", "attributeValue": "{10,20,100,21,40,200}", "displayOn": "true", "attributeName": "price" } ]
Why Avoid Duplicate Keys?
As mentioned earlier, duplicate keys violate JSON specifications. If you try to create an object with two attributeValue keys, parsers will typically discard all but the last entry. This leads to data loss and inconsistent behavior across tools, so combining values into a single field is always the safer choice.
内容的提问来源于stack exchange,提问作者Jess

