【问题标题】:How to convert the below result into my required format如何将以下结果转换为我需要的格式
【发布时间】:2021-10-24 00:42:09
【问题描述】:

我想将以下结果重新格式化为我需要的格式。 当前结果:

{
'1': [
{ Resource_id: 1, Rolemaching: 5 },
{ Resource_id: 1, Rolemaching: 5 },
{ Resource_id: 1, Technologymaching: 25 },
{ Resource_id: 1, Technologymaching: 25 },
{ Resource_id: 1, Educationmaching: 1.6666666666666667 },
{ Resource_id: 1, Educationmaching: 3.3333333333333335 }
],
'2': [ { Resource_id: 2, Domainmaching: 10 } ]
}

我需要的格式

{
Resource_id : 1
Rolemaching : 10,
Technologymaching:25,
Educationmaching : 4.5
}
{
Resource_id : 2,
Domainmaching : 10
}

【问题讨论】:

  • 到目前为止你有什么尝试?

标签: node.js arrays json


【解决方案1】:

我不确定您需要从“我需要的格式”示例中推断出什么。但如果您需要对所有属性求和(Resource_id 除外),这是一个变体:

const data1 = {
  '1': [
    { Resource_id: 1, Rolemaching: 5 },
    { Resource_id: 1, Rolemaching: 5 },
    { Resource_id: 1, Technologymaching: 25 },
    { Resource_id: 1, Technologymaching: 25 },
    { Resource_id: 1, Educationmaching: 1.6666666666666667 },
    { Resource_id: 1, Educationmaching: 3.3333333333333335 },
  ],
  '2': [
    { Resource_id: 2, Domainmaching: 10 },
  ],
};

const data2 = Object.values(data1).map(
  array => array.reduce(
    (acc, { Resource_id, ...rest }) => {
      acc.Resource_id ??= Resource_id;
      for (const [key, value] of Object.entries(rest)) {
        acc[key] ??= 0;
        acc[key] += value;
      }
      return acc;
    },
    {},
  )
);

console.log(data2);

输出:

[
  {
    "Resource_id": 1,
    "Rolemaching": 10,
    "Technologymaching": 50,
    "Educationmaching": 5
  },
  {
    "Resource_id": 2,
    "Domainmaching": 10
  }
]

【讨论】:

    猜你喜欢
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 2021-03-31
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    相关资源
    最近更新 更多