【问题标题】:Merge values to an array based on similar object key javascript [closed]基于类似的对象键javascript将值合并到数组[关闭]
【发布时间】:2022-01-14 23:34:42
【问题描述】:

我有这样的回报

[
{
    "tripw3": "1"
},
{
    "tripw1": "2"
},
{
    "tripw1": "3"
},
{
    "tripw2": "4"
},
{
    "tripw2": "5"
},
{
    "tripw3": "6"
},
{
    "tripw3": "7"
}]

我想让上面的结果变成

[
{
 tripw3: ["1", "6", "7"],
 tripw2: ["4", "5"],
 tripw1: ["3", "2"]
}]

直到现在我仍然很困惑如何做到这一点。

【问题讨论】:

  • 你数组中的所有对象都有这个结构吗?这意味着他们总是有tripw4 并且只有tripw4
  • 不,我忘记添加了。 tripw4只是一个例子,有时可以是tripw4和tripw3的混合,tripw2等等
  • 查看Array.reduce
  • @NovalRaihan 请给我们一个更好更通用的例子。

标签: javascript reactjs typescript


【解决方案1】:

您可以使用reduceObject.keysforEach 轻松获得结果

const arr = [
  {
    tripw4: "1",
  },
  {
    tripw4: "2",
  },
  {
    tripw4: "3",
  },
  {
    tripw4: "4",
  },
  {
    tripw4: "5",
  },
  {
    tripw4: "6",
  },
  {
    tripw4: "7",
  },
];

const result = [arr.reduce((acc, curr) => {
  Object.keys(curr).forEach((k) => acc[k] ? acc[k].push(curr[k]) : (acc[k] = [curr[k]]));
  return acc;
}, {})];

console.log(result);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-08
    • 2015-06-08
    • 2022-12-18
    • 2018-05-03
    • 2010-11-10
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    相关资源
    最近更新 更多