JavaScript:将 Json 数据数组更改为新格式

2023-12-28

我正在尝试使用需要以多种方式进行更改的 json 数据。

我当前的json数据如下:

{
  "file1": {
    "function1": {
      "calls": {
        "105:4": {
          "file": "file2",
          "function": "function5"
        },
        "106:4": {
          "file": "file2",
          "function": "function6"
        }
      },
      "lines1": {
        "123": "102:0",
        "456": "105:8"
      },
      "lines2": {
        "102:0": [
          "102:0"
        ],
        "105:4": [
          "106:4",
          "107:1"
        ],
        "106:4": [
          "107:1"
        ]
      }
    }
  }
}

但我想要的数据如下:

{
  "name": "program",
  "children": [
    {
      "name": "file1",
      "children": [
        {
          "name": "function1",
          "calls": [
            {
              "line": 105,
              "file": "file2",
              "function": "function5"
            },
            {
              "line": 106,
              "file": "file2",
              "function": "function6"
            }
          ],
          "lines1": [
            102,
            105
          ],
          "lines2": [
            [
              102,
              102
            ],
            [
              105,
              106,
              107
            ],
            [
              106,
              107
            ]
          ],
          "group": 1
        }
      ],
      "group": 1
    }
  ],
  "group": 0
}

这里,文件的数量和功能都比较多。名字的值是用户定义的。群组信息取决于父子。每个文件都会有一个组升序的组号,并且文件内的所有函数也将具有相同的组号。对于行的值,采用 : 之前的第一部分(104:4 变为 104)。

到目前为止,我已尝试使用以下代码,该代码不完整并且无法正确处理组信息。

function build(data) {
    return Object.entries(data).reduce((r, [key, value], idx) => {
      const obj = {
        name: 'program',
        children: [],
        group: 0,
        lines: []
      }

      if (key !== 'lines2) {
        obj.name = key;
        obj.children = build(value)
          if(!(key.includes(":")))
          obj.group = idx + 1;
      } else {
        if (!obj.lines) obj.lines = [];
        Object.entries(value).forEach(([k, v]) => {
          obj.lines.push([k, ...v].map(e => e.split(':').shift()))
        })
      }

      r.push(obj)
      return r;
    }, [])
  }

  const result = build(data);
  console.log(result);

如果您能帮助我,我将非常感激。在此先感谢您的时间。


假设您的输入结构如您的问题所示一致定义(即不需要“安全检查”等),那么您可以使用以下组合来解决此问题Object.entries() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries, Array.map() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map and 扩展语法 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax如下所示。

有关如何实现这一目标的详细信息,请参阅此代码片段中的内联文档:

function transformData(data, programName) {

  /* Define local parse helper to extract number from NUMBER:STRING format */    
  const parseHelper = (str) => Number.parseInt(str.split(':')[0]);
      
  /* Define local parse helper to extract group number from STRINGNUMBER 
  format */    
  const parseGroup = (str) => Number.parseInt(str.replace(/^[a-z]+/,""))
      
  /* Create a root object with specified program name */
  return {
    name : programName,
    
    /* Iterate each file name and object entry of input */
    children : Object.entries(input).map(([fileName, fileObject]) => {

      /* Iterate function name and object of current file object */
      const fileChildren = Object.entries(fileObject)
        .map(([functionName, functionObject]) => {

        /* Iterate function name and object of current file object */
        const lines = Object.entries(functionObject)
          .reduce((target, [functionKey, functionValue]) => {

            if(functionKey === "calls") {

              /* If function key is calls, interpret this value as data to be
              transformed to desired calls object shape */
              const calls = Object.entries(functionValue)
                .map(([callKey, callObject]) => {

                return {
                  line : parseHelper(callKey),
                  file : callObject['file'],
                  function : callObject['function']
                }
              });
              
              /* Inject calls object into lines result */
              return {
                ...target,
                calls
              };
            }
            else {

              /* Otherwise, interpret this value as data to be transformed to 
                 desired lines object shape */
              const lineValues = Object.entries(functionValue)
                .map(([key, value]) => {

                /* If value is an array, map key/value pair to a nested array
                   in resulting linesValues array */
                return Array.isArray(value) ? [key, ...value]
                 .map(parseHelper) : parseHelper(value)
              })

              /* Inject line values into function key of result */
              return {
                ...target,
                [functionKey] : lineValues
              }
            }

        }, {});
        
        /* Inject lines into function result */
        return {
          name : functionName,
          ...lines,
          group : parseGroup(functionName)
        }
      });

      /* Map file object to name/children pairing */
      return { 
        name : fileName,
        children : fileChildren,
          group : parseGroup(fileName)
      }
    }),
    
    group : 0
  }
}

const input = {
  "file1": {
    "function1": {
      "calls": {
        "105:4": {
          "file": "file2",
          "function": "function5"
        },
        "106:4": {
          "file": "file2",
          "function": "function6"
        }
      },
      "lines1": {
        "123": "102:0",
        "456": "105:8"
      },
      "lines2": {
        "102:0": [
          "102:0"
        ],
        "105:4": [
          "106:4",
          "107:1"
        ],
        "106:4": [
          "107:1"
        ]
      }
    }
  }
};

console.log(transformData(input, "program"))

希望有帮助!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JavaScript:将 Json 数据数组更改为新格式 的相关文章

随机推荐

  • JavaScript atan2() 函数未给出预期结果

    通常 极坐标从 0 到 到 2 实际上就在 2 之前 因为它又等于 0 然而 当使用 JavaScriptatan2 函数 我得到了一个不同的 奇怪的范围 Cartesian X Cartesian Y Theta 1 0 0 0 1 1
  • 运行我自制的旋转算法时得到不正确的图片输出

    为了更好地理解图像处理的工作原理 我决定创建自己的图像旋转算法 而不是使用 cv2 rotate 但是 我遇到了奇怪的图片裁剪和像素错位问题 我认为这可能与我的填充有关 但也可能有其他错误 import cv2 import math im
  • 在 MATLAB 中循环内部绘图

    我正在做这样的事情 a 1 100 for i 1 100 plot 1 i a 1 i end 我的问题是 直到循环完成后才会显示绘图 如何在每次迭代中显示 更新绘图 Use DRAWNOW http www mathworks com
  • 使用 Aurelia 的 Fetch Client 时 Azure Translator API(认知服务)上出现 CORS 错误

    我尝试使用来自 Windows Azure 的非常基本的 API 调用来翻译一些文本 他们给出了一个快速入门示例代码 https learn microsoft com en us azure cognitive services tran
  • WPF - 应用前景时默认按钮禁用样式

    按钮应用了一个Foreground当它被启用时 如果设置为Disabled 则默认Button为DisabledForeground需要申请
  • 按值传递 vs 按引用传递(两者之间内存空间分配的差异)

    在 C 中 我们使用引用传递 我们引用从参数传递到函数参数的任何地址 这本质上是一个指针 对吗 因此 虽然它们本质上是相同的东西 别名等等 但指针不是也需要内存空间吗 因此 无论我们在参数函数中拥有什么 都不应该让我们调用 B 指向所传递的
  • 多维数组符号之间的差异(object[][] 和 object[])

    我想知道在 C 中定义多维数组的两种方法有什么区别 您可以使用object and object 处理多维数组 功能上有区别吗 The object 是数组数组的表示法 第二个object 是一个二维数组 主要区别是第一个可以包含不同长度的
  • angularJS ng-model 输入类型号到 rootScope 未更新

    我的输入类型编号设置为
  • C# Decimal.GetHashCode() 和 Double.GetHashCode() 相等

    为什么会这样17m GetHashCode 17d GetHashCode m 十进制 d 双精度 另外 正如预期的那样17f GetHashCode 17d GetHashCode f 浮点数 对于 net3 5 和 net4 0 来说似
  • CSS悬停图像位置更改

    我确信这是超级愚蠢的事情 但现在我已经被困了一段时间 所以 我在网站上有图像 我希望它们在悬停时稍微移动 所以我在 HTML 中有 a href someaddress img class thumb src somefile a 在 CS
  • Dart SDK未配置

    我安装了 Flutter 并设置了 Android Studio 然后我在 GitHub 上克隆了一个 flutter 的示例 https github com flutter flutter https github com flutte
  • Linux 中的 Qt 线程问题

    我在我的项目中使用 Qt 进行开发已经有一段时间了 我们开始转向更加面向线程的设计 在将一些 GL 渲染小部件移动到其他线程后 我发现了一些非常奇怪的行为 看起来 如果 GL Widget 在接受用户输入的小部件 例如 QTextEdit
  • Android:如何加载PDF?

    有没有办法从浏览器或 WebView 中的 Asset URL 或任何其他方式加载 PDF 文件 目前还没有本地方法可以做到这一点 但是 您可以编写自己的 pdf 查看器活动 另外 请查看复制Go阅读器 http www cerience
  • 在 git 交互式变基期间添加了新文件,变基中止,新文件丢失

    我之前在几个节点上提交了 git rebase i 我添加了一些我打算添加到该提交中的新文件 看起来我在错误的节点上 所以我立即执行了 git rebase abort 这些新文件现在完全消失了 在引用日志中 看起来像是发出了删除命令 删除
  • Telegram markdown 语法:粗体 * 和 * 斜体? (2018年9月)

    通过查看Telegram 的 Markdown 语法 Wiki 页面 https sourceforge net p telegram wiki markdown syntax 创建文本应该相对容易粗体和斜体 在那里 它说 this is
  • Vuex Store 模块访问状态

    我想知道如何从另一个文件访问模块存储 状态 到目前为止 这是我的代码 store index js import Vuex from vuex import categories from modules categories Vue us
  • 允许在子命令后使用 argparse 全局标志

    我正在使用 argparse 构建带有子命令的命令 mycommand GLOBAL FLAGS 子命令 FLAGS 我希望全局标志无论在子命令之前还是之后都可以工作 有没有一种干净的方法来做到这一点而不涉及重复代码 例如 parser a
  • 如何更改 Material UI 自动完成弹出窗口的宽度

    当使用Select https material ui com api select 在 Material UI 中 有一个名为 autoWidth 的道具 它设置弹出窗口的宽度以匹配菜单内项目的宽度 是否有类似的选项自动完成 https
  • 基于骨骼运动的 Kinect 3D 手势识别 - 存在哪些库?

    Kinect 有哪些手势识别库 如果有 现在我正在使用 OpenNI 记录骨骼运动 但不确定如何从该运动到触发离散动作 我的问题可能像姿势检测一样简单 但也可能像基于时间的运动一样复杂 即检测他们何时将手绕圈移动 具体取决于其难度 我见过的
  • JavaScript:将 Json 数据数组更改为新格式

    我正在尝试使用需要以多种方式进行更改的 json 数据 我当前的json数据如下 file1 function1 calls 105 4 file file2 function function5 106 4 file file2 func