JavaScript数组重复对象去重并合并属性值问题求助
Solution to Merge Duplicate Filter Entries into an Array
Nice question! The issue with using Object.assign here is that it overwrites properties with identical keys—so you end up only keeping the last filter value instead of grouping all of them. Let’s fix this by using Array.reduce() to iterate through your input array, collect all filter values into a single array, and preserve the other unique objects as-is.
Here’s a working implementation tailored to your needs:
// Your original input array const inputArray = [ {date_range_one: '2018-03-03+-+2018-05-01'}, {date_range_two: '2001-11-27+-+2018-05-01'}, {filter: '1'}, {filter: '4'}, {filter: '18'}, ]; // Transform the array to merge filter entries const transformedArray = inputArray.reduce((accumulator, currentObj) => { const [key] = Object.keys(currentObj); const value = currentObj[key]; if (key === 'filter') { // Check if we already have a filter entry in our result const existingFilter = accumulator.find(item => item.hasOwnProperty('filter')); if (existingFilter) { // Convert the string value to a number and add to the array existingFilter.filter.push(Number(value)); } else { // Create a new filter entry with an array holding the first value accumulator.push({ filter: [Number(value)] }); } } else { // For non-filter keys, just add the entire object directly to the result accumulator.push(currentObj); } return accumulator; }, []); console.log(transformedArray);
How this works:
- We use
reduce()to build our result array step by step. - For each object in the input:
- If the key is
filter, we check if we already have afilterobject in our result. If yes, we append the new value (converted to a number) to its array. If not, we create a newfilterobject with an array containing the first value. - For all other keys (like
date_range_oneanddate_range_two), we simply add the entire object to the result array without modifications.
- If the key is
If you want a string instead of an array:
If you prefer filter to be a comma-separated string (e.g., {filter: "1,4,18"}) instead of an array, adjust the filter handling logic like this:
if (key === 'filter') { const existingFilter = accumulator.find(item => item.hasOwnProperty('filter')); if (existingFilter) { existingFilter.filter += `,${value}`; } else { accumulator.push({ filter: value }); } }
内容的提问来源于stack exchange,提问作者spirin88
相关产品推荐
相关产品推荐

