【问题标题】:Javascript Combine Items in An Array ObjectJavascript 在一个数组对象中组合项目
【发布时间】:2023-04-06 22:34:01
【问题描述】:

我发现 _.reduce 但它只保留一组信息。应该使用什么选项来组合类似的信息?

[
  {
    fruit: 'apple',
    'color': 'red'
  },
  {
    fruit: 'apple',
    'color': 'green'
  },
  {
    fruit: 'pear',
    'color': 'yellow'
  },
  {
    fruit: 'pear',
    'color': 'green'
  }
]

我想要的结果是:

var items = [
  {
    fruit: 'apple',
    'color': 'red', 'green'
  },
  {
    fruit: 'pear',
    'color': 'green', 'yellow'
  }
]

我目前使用 NodeJS 的代码是:

 let result = Object.values(json.reduce((c, {fruit,...r}) => {
   c[fruit] = c[fruit] || {fruit};
   c[fruit] = Object.assign(c[fruit], r);
   return c;
 }, {}));

【问题讨论】:

  • 由于您使用的是 lodash,请查看_.groupBy。您可能需要额外的后处理步骤来实现最终的数据结构,但_.groupBy 做了很多工作。

标签: javascript arrays node.js object


【解决方案1】:

这是一种运行时间为 O(n) 而不是 O(n^2) 的方法:

const arr = [
  {
    fruit: 'apple',
    'color': 'red',
  },
  {
    fruit: 'apple',
    'color': 'green',
  },
  {
    fruit: 'pear',
    'color': 'yellow',
  },
  {
    fruit: 'pear',
    'color': 'green',
  },
];
const map = arr.reduce((acc, o) => {
  if (acc[o.fruit]) {
    acc[o.fruit].push(o.color);
  } else {
    acc[o.fruit] = [o.color];
  }
  return acc;
}, {});
const result = Object.keys(map).map(k => ({ fruit: k, colors: map[k] }));
console.log(result);
return result;

请注意,正如尼克的回答中所指出的,差异对于小数组不会产生影响,但如果数组很大,或者转换本身包含在一个循环中,这可能很重要。

【讨论】:

    【解决方案2】:

    您可以为此使用数组reduce 方法。假设您的数组不是很长,在每次迭代中使用 find 方法应该不会太贵。如果它是一个超长数组,您可能会选择具有哈希表效率的中间对象。不过可能没必要。

    const arr = [
      {
        fruit: 'apple',
        'color': 'red'
      },
      {
        fruit: 'apple',
        'color': 'green'
      },
      {
        fruit: 'pear',
        'color': 'yellow'
      },
      {
        fruit: 'pear',
        'color': 'green'
      }
    ];
    
    const combined = arr.reduce((acc, el) => {
      const fruit = acc.find(item => item.fruit === el.fruit);
      if (fruit) {
        fruit.colors.push(el.color)
      } else {
        acc.push({ fruit: el.fruit, colors: [el.color] });
      }
      return acc;
    }, []);
    
    console.log(combined);

    【讨论】:

      【解决方案3】:

      使用简单的forEach 并构建唯一键的对象并使用Object.values 获取值。

      const data = [
        {
          fruit: "apple",
          color: "red"
        },
        {
          fruit: "apple",
          color: "green"
        },
        {
          fruit: "pear",
          color: "yellow"
        },
        {
          fruit: "pear",
          color: "green"
        }
      ];
      
      const res = {};
      
      data.forEach(
        item =>
          (res[item.fruit] =
            item.fruit in res
              ? { ...res[item.fruit], color: [...res[item.fruit].color, item.color] }
              : { fruit: item.fruit, color: [item.color] })
      );
      
      const output = Object.values(res);
      
      console.log(output);

      【讨论】:

        猜你喜欢
        • 2018-11-17
        • 1970-01-01
        • 2012-03-04
        • 2016-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多