【问题标题】:re-organizing array of objects重新组织对象数组
【发布时间】:2021-04-08 02:35:50
【问题描述】:

所以我有一个对象数组,其中包含不同项目中不同活动的信息。 它看起来像这样

const input = [
  {
    Project: 1,
    ID: "1-1",
  },
  {
    Project: 1,
    ID: "1-2",
  },
  {
    Project: 2,
    ID: "2-1",
  },
];

从这里,我想去这里

output = [{
    Project: 1,
    ID1: 1 - 1,
    ID2: 1 - 2,
  },
  {
    Project: 1,
    ID1: 2 - 1,
  },
];

这是我目前所拥有的:

let currentProject = ''
let output = []


for (const e of input) {
  let counter
  let outputObj = {}

  if (currentProject !== e.Project) {
    output.push(outputObj)
    counter = 1
    outputObj = {}

    outputObj.projectNum = e.Project

    currentProject = e.Project
  }

  if (currentProject == e.Project) {
    outputObj['ID' + counter] = e.ID
    counter++
  }

}

这是我要返回的内容:

output = [{
    Project: 1,
    ID1: 1 - 1
  },
  {
    Project: 1,
    ID1: 2 - 1
  }
]

我不确定是什么问题,尝试了几次以解决它。 有人可以帮我克服困难吗? 任何帮助将不胜感激。

【问题讨论】:

  • 为什么不使用 ID 数组而不是 ID1ID2
  • 您每次通过循环创建一个新的outputObj,而不仅仅是在项目更改时。在循环外初始化它。
  • 因为这些对象会被一个一个地输入到一个函数中去执行一些其他的任务。
  • 这段代码实际上不会产生你说你要回来的输出。你确定这是你正在使用的例程吗?
  • 您可以分两步完成此操作 1. 将 IDs 分组为 Project 2. 将字符串转换为表达式

标签: javascript arrays object


【解决方案1】:

您可以使用reduceObject.keys 实现此目的

const input = [{
    Project: 1,
    ID: "1-1",
  },
  {
    Project: 1,
    ID: "1-2",
  },
  {
    Project: 2,
    ID: "2-1",
  },
];

const result = input.reduce((acc, curr) => {
  const { Project, ID } = curr;
  const obj = acc.find((el) => el.Project === Project);
  if (obj) {
    const length = Object.keys(obj).length;
    obj[`ID${length}`] = ID;
  } else {
    acc.push({ Project, [`ID${1}`]: ID });
  }
  return acc;
}, []);

console.log(result);

【讨论】:

    【解决方案2】:

    你可以试试这个。

    const input=[{Project:1,ID:"1-1",},{Project:1,ID:"1-2",},{Project:2,ID:"2-1"}];
    
    let temp = {}; 
    input.map(v=>(temp[v.Project] ??= []).push(v.ID));
    let output = Object.keys(temp).map(k=>{
        let json = {Project:k};
        temp[k].map((v,k)=>json['ID'+(Number(k+1))]=v);
        return json;
    });
    console.log(output);
    

    你会得到结果。

    [
        { Project: '1', ID1: '1-1', ID2: '1-2' },
        { Project: '2', ID1: '2-1' }
    ]
    

    【讨论】:

      【解决方案3】:

      打算实现这一点的方式假定来自同一 id 的每个项目都按顺序分组。

      虽然@decpk answer 处理线性搜索,但出于性能原因,我宁愿先使用字典,然后转换为数组,还可以使用字段 n 跟踪 id 数量。

      const input = [
          {
              Project: 1,
              ID: "1-1",
          },
          {
              Project: 1,
              ID: "1-2",
          },
          {
              Project: 2,
              ID: "2-1",
          },
      ];
      
      const projects = {}
      
      for (const e of input) {
          let pid = e.Project
          let project = projects[pid]
          //First time seeing this project
          if (!project) {
              projects[pid] = { Project: pid, n: 1, ID1: e.ID }
          }
          //insert more ID
          else {
              project.n += 1
              project[`ID${project.n}`] = e.ID
          }
      }
      
      //And now converting the object to array, removing the 'n' field
      const output = Object.keys(projects).map(pid => {
          const obj = projects[pid]
          delete obj.n
          obj.Project = pid
          return obj
      })

      【讨论】:

        【解决方案4】:

        你可以试试这个方法 - O(n) 时间复杂度

        const number = Object.keys(acc[Project]).length; // Define key format by number of existing property.
        const key = `ID${number}`;
        

        而不是使用count 变量。

        const input=[{Project:1,ID:"1-1",},{Project:1,ID:"1-2",},{Project:2,ID:"2-1",}];
        
        const output = input.reduce((acc, {Project, ID}) => 
        {
          acc[Project] ??= {Project}; // Get exist object or create new one
        
          const number = Object.keys(acc[Project]).length; // Define key format by number of existing property.
          const key = `ID${number}`;
          acc[Project][key] = ID;
          
          return acc;
        }, {});
        
        console.log(Object.values(output));

        输出:

        [
          {
            "Project": 1,
            "ID1": "1-1",
            "ID2": "1-2"
          },
          {
            "Project": 2,
            "ID1": "2-1"
          }
        ]
        

        【讨论】:

        • 这能回答你的问题吗?如果您需要任何帮助,请告诉我^^! @profiter
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-12
        相关资源
        最近更新 更多