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

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 a filter object in our result. If yes, we append the new value (converted to a number) to its array. If not, we create a new filter object with an array containing the first value.
    • For all other keys (like date_range_one and date_range_two), we simply add the entire object to the result array without modifications.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:49:42