【问题标题】:split object to object arrays in JS在JS中将对象拆分为对象数组
【发布时间】:2022-01-22 01:55:16
【问题描述】:

您好,我无法将此对象转换为对象数组。

有数字和原因字段,目前是一个','分隔的字符串。它们应该被分解成它们自己的对象。示例数据集和我要归档的内容可以在下面的coden-p中看到。

// start value
const data = {
  date: "2021-09-07 10:28:34,2021-09-08 14:45:22",
  startDate: "2021-09-07 00:00:00,2021-09-08 14:45:22"
  id: "111111"
  number: "1,9"
  reason: "Autres,Autres"

}

// what I want to archive:
  const res = [{
    date: "2021-09-07 10:28:34",
    startDate: "2021-09-07 00:00:00",
    id: 11111,
    number: 1,
    reason: "Autres"
  } {
    date: "2021-09-08 14:45:22",
    startDate: "2021-09-08 14:45:22",
    id: 11111,
    number: 9,
    reason: "Autres"
  }]

【问题讨论】:

  • 到目前为止,您尝试了哪些方法来自行解决此问题? .split() 结合一些循环应该已经让你进入正确的方向。
  • @VincentMenzel 为什么你完全重写了这个问题?什么是“对象数组”?没有任何输出/结果但有语法错误的 sn-p 如何改进这个问题?
  • 我想修复它们,但是队列目前已满,所以我必须等待。

标签: javascript arrays split


【解决方案1】:
  1. 使用reduce 方法和spread 运算符将带有字符串组合列的原始对象投影到具有splitted 列作为数组的对象中。

    1a。通过filtering outid 列从原始对象中提取列名。

    1b。投影过程中,统计行数。

  2. 使用上述计数器迭代行,为每一行生成一个新对象,使用当前迭代索引获取相关列值。

    const original = {
      date: "2021-09-07 10:28:34,2021-09-08 14:45:22",
      startDate: "2021-09-07 00:00:00,2021-09-08 14:45:22",
      id: "111111",
      number: "1,9",
      reason: "Autres,Autres"
    };
    
    function split(obj) {
      const columnNames = Object.keys(obj).filter(key => key !== "id");
      const singleWithSplitted = columnNames.reduce((result, columnName) => {
        const splittedArray = obj[columnName].split(",");
        return ({
          rowsCount: Math.max(result.rowsCount, splittedArray.length),
          table: { ...result.table,
            [columnName]: splittedArray
          }
        });
      }, {
        rowsCount: 0
      });
      const arr = [];
      for (i = 0; i < singleWithSplitted.rowsCount; i++) {
        const result = {
          id: obj.id
        };
        columnNames.forEach((columnName) => {
          result[columnName] = singleWithSplitted.table[columnName][i];
        });
        arr.push(result);
      };
      return arr;
    }
    console.log(split(original));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 2015-10-16
    • 2021-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多