首页 > 解决方案 > 转换对象数组和连接对象值

问题描述

我有一个需要转换为新对象数组的对象数组。有没有一种方法可以在不手动定义"texas""california"定义新的对象数组时完成?

这是我的原始数据:

const data = [
    {
      year: "2005",
      texas: 6.984323232343243
    },
    {
      year: "2006",
      texas: 8.507629970573532
    },
    {
      year: "2005",
      california: 8.422823214889691
    },
    {
      year: "2006",
      california: 9.456857576876532
    }
  ];

我需要它看起来像这样:

const newData = [
    {
      year: 2005,
      texas: 6.984323232343243,
      california: 8.422823214889691
    },
    {
      year: 2006,
      texas: 8.507629970573532,
      california: 9.456857576876532
    }
  ];

我试图对这些对象进行分组,然后取消分组,但我只能进行分组并且似乎无法弄清楚如何按照我需要的方式取消分组。有没有办法在不先分组的情况下做到这一点?

const data = [
    {
      year: "2005",
      texas: 6.984323232343243
    },
    {
      year: "2006",
      texas: 8.507629970573532
    },
    {
      year: "2005",
      california: 8.422823214889691
    },
    {
      year: "2006",
      california: 9.456857576876532
    }
  ];
const groupByReduce = (array, key) => {
    return array.reduce((result, currentValue) => {
      (result[currentValue[key]] = result[currentValue[key]] || []).push(
        currentValue
      )
      return result
    }, {});
  };
const newData = groupByReduce(data, "year");

console.log(newData);
.as-console-wrapper { max-height: 100% !important; top: 0; }

标签: javascript

解决方案


你可以reduce这样使用——

const data = [
  {year: "2005", texas: 6.984323232343243},
  {year: "2006", texas: 8.507629970573532},
  {year: "2005", california: 8.422823214889691},
  {year: "2006", california: 9.456857576876532}
];

let res = data.reduce((a, c) => ({...a, [c.year]: {...a[c.year], ...c}}), {});

res = Object.values(res);

console.log(res);
.as-console-wrapper {min-height: 100%!important; top: 0}


推荐阅读