递归重命名对象键

2024-01-11

我有一个递归函数来重命名对象的键名称,但我无法弄清楚如何重命名其中 2 个键(问题键是对象)

我认为问题在于我正在检查对象类型,但此时如何重命名密钥?

实际的数组非常大,但下面是一个缩小版本。

任何帮助表示赞赏。

var keys_short = ['ch','d','u','tz'];
var keys_long = ['children','data','user_id','time_zone'];
function refit_keys(o){
    build = {};
    for (var i in o){
        if(typeof(o[i])=="object"){
            o[i] = refit_keys(o[i]);
            build = o;
        }else{
            var ix = keys_short.indexOf(i);
            if(ix!=-1){
                build[keys_long[ix]] = o[keys_short[ix]];
            }
        }
    }
    return build;
}

我的输入如下所示:

{
    "id":"1",
    "ch":[
        {
            "id":"3",
            "ch":[
            ],
            "d":{
                "u":"3",
                "tz":"8.00"
            }
        },
        {
            "id":"45",
            "ch":[
                {
                    "id":"70",
                    "ch":[
                        {
                            "id":"43",
                            "ch":[
                            ],
                            "d":{
                                "u":"43",
                                "tz":"-7.00"
                            }
                        }
                    ],
                    "d":{
                        "u":"70",
                        "tz":"-7.00"
                    }
                }
            ],
            "d":{
                "u":"45",
                "tz":"-7.00"
            }
        }
    ],
    "d":{
        "u":"1",
        "tz":"8.00"
    }
}

我的输出是这样的:

{
    "id":"1",
    "ch":[
        {
            "id":"3",
            "ch":[
            ],
            "d":{
                "user_id":"3",
                "time_zone":"8.00"
            }
        },
        {
            "id":"45",
            "ch":[
                {
                    "id":"70",
                    "ch":[
                        {
                            "id":"43",
                            "ch":[
                            ],
                            "d":{
                                "user_id":"43",
                                "time_zone":"-7.00"
                            }
                        }
                    ],
                    "d":{
                        "user_id":"70",
                        "time_zone":"-7.00"
                    }
                }
            ],
            "d":{
                "user_id":"45",
                "time_zone":"-7.00"
            }
        }
    ],
    "d":{
        "user_id":"1",
        "time_zone":"8.00"
    }
}

这里有几个问题。

一是你正在成为受害者隐式全局变量的恐怖 http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html未能申报您的build函数中的变量。

但逻辑也有问题,这里有一个最小的修改:

var keys_short = ["ch","d","u","tz"];
var keys_long = ["children","data","user_id","time_zone"];
function refit_keys(o){
    var build, key, destKey, ix, value;

    // Only handle non-null objects
    if (o === null || typeof o !== "object") {
        return o;
    }

    // Handle array just by handling their contents
    if (Array.isArray(o)) {
        return o.map(refit_keys);
    }

    // We have a non-array object
    build = {};
    for (key in o) {
        // Get the destination key
        ix = keys_short.indexOf(key);
        destKey = ix === -1 ? key : keys_long[ix];

        // Get the value
        value = o[key];

        // If this is an object, recurse
        if (typeof value === "object") {
            value = refit_keys(value);
        }

        // Set it on the result using the destination key
        build[destKey] = value;
    }
    return build;
}

实例:

"use strict";
var input = {
    "id":"1",
    "ch":[
        {
            "id":"3",
            "ch":[
            ],
            "d":{
                "u":"3",
                "tz":"8.00"
            }
        },
        {
            "id":"45",
            "ch":[
                {
                    "id":"70",
                    "ch":[
                        {
                            "id":"43",
                            "ch":[
                            ],
                            "d":{
                                "u":"43",
                                "tz":"-7.00"
                            }
                        }
                    ],
                    "d":{
                        "u":"70",
                        "tz":"-7.00"
                    }
                }
            ],
            "d":{
                "u":"45",
                "tz":"-7.00"
            }
        }
    ],
    "d":{
        "u":"1",
        "tz":"8.00"
    }
};

var keys_short = ["ch","d","u","tz"];
var keys_long = ["children","data","user_id","time_zone"];
function refit_keys(o){
    var build, key, destKey, ix, value;

    // Only handle non-null objects
    if (o === null || typeof o !== "object") {
        return o;
    }

    // Handle array just by handling their contents
    if (Array.isArray(o)) {
        return o.map(refit_keys);
    }

    // We have a non-array object
    build = {};
    for (key in o) {
        // Get the destination key
        ix = keys_short.indexOf(key);
        destKey = ix === -1 ? key : keys_long[ix];

        // Get the value
        value = o[key];

        // If this is an object, recurse
        if (typeof value === "object") {
            value = refit_keys(value);
        }

        // Set it on the result using the destination key
        build[destKey] = value;
    }
    return build;
}

console.log(refit_keys(input));
.as-console-wrapper {
    max-height: 100% !important;
}

但我建议通过对象或对象使用映射,而不是并行数组Map:

// Object with no prototype to avoid false matches on `toString` and other built-ins
var mapShortToLong = Object.assign(Object.create(null), {
    "ch": "children",
    "d":  "data",
    "u":  "user_id",
    "tz": "time_zone"
});
function refit_keys(o){
    var build, key, destKey, value;

    // Only handle non-null objects
    if (o === null || typeof o !== "object") {
        return o;
    }

    // Handle array just by handling their contents
    if (Array.isArray(o)) {
        return o.map(refit_keys);
    }

    build = {};
    for (key in o) {
        // Get the destination key
        destKey = mapShortToLong[key] || key;

        // Get the value
        value = o[key];

        // If this is an object, recurse
        if (typeof value === "object") {
            value = refit_keys(value);
        }

        // Set it on the result using the destination key
        build[destKey] = value;
    }
    return build;
}

实例:

"use strict";
var input = {
    "id":"1",
    "ch":[
        {
            "id":"3",
            "ch":[
            ],
            "d":{
                "u":"3",
                "tz":"8.00"
            }
        },
        {
            "id":"45",
            "ch":[
                {
                    "id":"70",
                    "ch":[
                        {
                            "id":"43",
                            "ch":[
                            ],
                            "d":{
                                "u":"43",
                                "tz":"-7.00"
                            }
                        }
                    ],
                    "d":{
                        "u":"70",
                        "tz":"-7.00"
                    }
                }
            ],
            "d":{
                "u":"45",
                "tz":"-7.00"
            }
        }
    ],
    "d":{
        "u":"1",
        "tz":"8.00"
    }
};

// Object with no prototype to avoid false matches on `toString` and other built-ins
var mapShortToLong = Object.assign(Object.create(null), {
    "ch": "children",
    "d":  "data",
    "u":  "user_id",
    "tz": "time_zone"
});
function refit_keys(o){
    var build, key, destKey, value;

    // Only handle non-null objects
    if (o === null || typeof o !== "object") {
        return o;
    }

    // Handle array just by handling their contents
    if (Array.isArray(o)) {
        return o.map(refit_keys);
    }

    build = {};
    for (key in o) {
        // Get the destination key
        destKey = mapShortToLong[key] || key;

        // Get the value
        value = o[key];

        // If this is an object, recurse
        if (typeof value === "object") {
            value = refit_keys(value);
        }

        // Set it on the result using the destination key
        build[destKey] = value;
    }
    return build;
}

console.log(refit_keys(input));
.as-console-wrapper {
    max-height: 100% !important;
}

或者在现代 JavaScript 中:

// Using a `Map` here to provide a `Map` example, but you can ue an object as
// in the previous ones if you prefer if the keys are strings
const mapShortToLong = new Map([
    ["ch", "children"],
    ["d",  "data"],
    ["u",  "user_id"],
    ["tz", "time_zone"],
]);
function refit_keys(o){
    // Only handle non-null objects
    if (o === null || typeof o !== "object") {
        return o;
    }

    // Handle array just by handling their contents
    if (Array.isArray(o)) {
        return o.map(refit_keys);
    }

    const build = {};
    for (const key in o) {
        // Get the destination key
        const destKey = mapShortToLong.get(key) || key;

        // Get the value
        let value = o[key];

        // If this is an object, recurse
        if (typeof value === "object") {
            value = refit_keys(value);
        }

        // Set it on the result using the destination key
        build[destKey] = value;
    }
    return build;
}

实例:

"use strict";
var input = {
    "id":"1",
    "ch":[
        {
            "id":"3",
            "ch":[
            ],
            "d":{
                "u":"3",
                "tz":"8.00"
            }
        },
        {
            "id":"45",
            "ch":[
                {
                    "id":"70",
                    "ch":[
                        {
                            "id":"43",
                            "ch":[
                            ],
                            "d":{
                                "u":"43",
                                "tz":"-7.00"
                            }
                        }
                    ],
                    "d":{
                        "u":"70",
                        "tz":"-7.00"
                    }
                }
            ],
            "d":{
                "u":"45",
                "tz":"-7.00"
            }
        }
    ],
    "d":{
        "u":"1",
        "tz":"8.00"
    }
};

// Using a `Map` here to provide a `Map` example, but you can ue an object as
// in the previous ones if you prefer if the keys are strings
const mapShortToLong = new Map([
    ["ch", "children"],
    ["d",  "data"],
    ["u",  "user_id"],
    ["tz", "time_zone"],
]);
function refit_keys(o){
    // Only handle non-null objects
    if (o === null || typeof o !== "object") {
        return o;
    }

    // Handle array just by handling their contents
    if (Array.isArray(o)) {
        return o.map(refit_keys);
    }

    const build = {};
    for (const key in o) {
        // Get the destination key
        const destKey = mapShortToLong.get(key) || key;

        // Get the value
        let value = o[key];

        // If this is an object, recurse
        if (typeof value === "object") {
            value = refit_keys(value);
        }

        // Set it on the result using the destination key
        build[destKey] = value;
    }
    return build;
}

console.log(refit_keys(input));
.as-console-wrapper {
    max-height: 100% !important;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

递归重命名对象键 的相关文章

  • Blueimp jQuery 文件上传,传递额外的表单数据

    我可以使用一些帮助 我已经设法使 blueimp jQuery 文件上传为我工作 但我仍然绝对是一个新手 我对 jQuery 等知之甚少 所以请尝试将其清晰明了地提供给我尽可能简单 我会尝试具体一点 好的 我想实现的是人们可以上传照片 并为
  • History.replaceState 仍然向“浏览历史记录”添加条目

    具体来说 调用以下代码片段 history replaceState undefined undefined value 正确地不会影响当前页面的后退按钮行为 但是will在 浏览历史记录 页面添加一个条目 这是我不想要的 下图是 Chro
  • 带有嵌入式 Ruby 的 Javascript:如何安全地将 ruby​​ 值分配给 javascript 变量

    我在页面的 javascript 块中有这一行 res foo 处理这种情况的最佳方法是什么 ruby var里面有单引号吗 否则会破坏 JavaScript 代码 我想我会用红宝石JSON http json org ruby var 上
  • Bootstrap:下拉菜单无法通过 jQuery 单击打开

    我正在创建一个包含多行的表 所有行都有一个 选项 按钮 该按钮应该显示下拉上下文菜单 为了使代码更短 我使用了一个div以便将其重用为上下文菜单的通用标记 我正在使用 Bootstrap 5 1 3 和 jQuery 3 6 0 以下是我的
  • 如何在参数上使用 .reduce() 而不是特定的数组或对象?

    我想定义一个函数 flatten 将多个元素展平为一个数组 我知道以下是不可能的 但本质上我想这样做 var flatten function var flattened arguments reduce function acc elem
  • 如何用 jQuery 替换击键?

    我需要能够用 jQuery 替换击键 当按下右箭头时 我希望改为按下 Tab 键 到目前为止我有
  • 将 Isotope 与通过 XML 和 jQuery 加载的对象一起使用。这可能吗?

    我正在使用 XML 和 jQuery 加载对象 并尝试连接到同位素 但似乎这是不行的 这可能吗 我尝试了许多不同的解决方案 但似乎找不到有效的解决方案 这就是我所拥有的 我已经尝试过同位素中的回调函数 但仍然没有运气 我用 XML 调用我的
  • 正则表达式 - 避免表达式中出现字符串

    我正在尝试创建一个应该匹配以下情况的正则表达式 如果单词完全匹配 first second third 那么匹配应该失败 但如果它周围有任何字符 那么应该匹配该字符串 我还需要避免字符串中的某些字符集 如果这些字符是字符串的一部分 则匹配结
  • 有没有相互递归的例子?

    是否有递归函数调用另一个函数 该函数也调用第一个函数 的示例 例子 function1 do something function2 do something function2 do something function1 do some
  • 用于导出到 CSV/Excel 的数据 URI(无服务器端请求):浏览器支持/限制?

    以下问题 Javascript 或 Flash 导出至 CSV Excel https stackoverflow com questions 8150516 javascript or flash export to csv excel
  • 如何检查jquery数据表中的每个复选框?

    我有一个第一列带有复选框的表格 我使用 jQuery DataTable 插件显示我的表格 我制作了 2 个链接来选择 取消选择每个复选框 这是选择全部的一个 a href Select all a 和 JavaScript functio
  • CryptoJS 和 Pycrypto 一起工作

    我正在使用 CryptoJS v 2 3 加密 Web 应用程序中的字符串 并且需要在服务器上使用 Python 对其进行解密 因此我使用 PyCrypto 我觉得我错过了一些东西 因为我无法让它工作 这是JS Crypto AES enc
  • IE6 丢失查询字符串

    我有一个使用 javascript 从查询字符串中获取值的页面window location 从网络服务器运行时效果很好 但如果我通过将其放在地址栏中使用 IE6 在本地运行它 c mysite index htm 网站创建的任何查询字符串
  • 有不同图像尺寸的缩略图 Bootstrap

    我想要包含不同大小和不同文本量的图像的缩略图 但我希望它们都具有相同的大小 像这样来自 Bootstrap 站点的示例 http getbootstrap com components thumbnails custom content 下
  • Tween JS 基础知识之三个 JS 立方体

    我是 Tween JS 的新手 尝试使用 Tween 制作一个向右移动的简单动画 下面是我在 init 函数中的代码 我使用的是三个 JS var geometry new THREE CylinderGeometry 200 200 20
  • 如何在 JavaScript 中设置/更新 String 对象的值

    我有一个具有一些属性的对象字符串对象 var obj foo new String bar 我在用字符串对象因为我需要在对象上存储额外的子属性 同时仍然能够获取字符串值 obj foo baz baz obj foo gt bar 我觉得问
  • nvd3.js - 无法更改折线图中线条的颜色

    我正在尝试更改 nvd3 折线图不同线条的颜色here http nvd3 org livecode index html codemirrorNav但我无法理解该怎么做 我想将示例中的 2 条线的颜色更改为绿色和青色 我试过 nv add
  • 加载 Ember.View 的内容后初始化 jQuery 插件

    DEBUG Ember VERSION 1 0 0 rc 6 ember js DEBUG Handlebars VERSION 1 0 0 rc 4 ember js DEBUG jQuery VERSION 1 9 1 控制器是一个Em
  • Javascript / jQuery - 转换特殊 html 字符

    我有一个pre元素中包含一些 html 代码 该代码中有特殊字符 例如 lt 所以它不会破坏页面 然后我有一个 javascript 函数 它获取此 pre 元素的内容 突出显示它 使用 codemirror 并用突出显示的文本替换元素内容
  • html5 canvas 使用图像作为蒙版

    是否可以使用具有形状的图像作为整个画布或画布内图像的蒙版 我想将图像放置在画布中 并在图像上添加蒙版 然后将其另存为新图像 您可以使用 source in globalCompositeOperation 将黑白图像用作蒙版 首先 将蒙版图

随机推荐

  • 线程安全的多文件写入

    我有一个守护进程 它接受套接字连接并读取或写入一组动态文件 具体取决于连接的性质 因为我的守护进程是多线程的 所以存在同一个文件可能被多个线程写入的可能性 因为我的文件列表是动态的而不是固定的 所以我不确定如何防止一个线程碰撞另一个线程 出
  • 在多个 return 语句的情况下,使用 `std::move` 返回是否明智?

    我知道返回通常不是一个好主意std move i e bigObject foo bigObject result return std move result 而不是简单地 bigObject foo bigObject result r
  • 列数与计数器列性能

    我想知道获取特定列族中的列数的最佳方法是什么 我可以直接获取列数 但我不确定这是否是有效的解决方案 另一方面 我可以维护另一个列族 其中包含一个包含列数的计数器列 您有遇到类似问题的经验吗 http wiki apache org cass
  • Fortran函数解释

    我在 Fortran 中有这个函数 我正在尝试用 C 重新编码它 C C FUNCTION POLY C FUNCTION POLY N A X DIMENSION A N C POLY 0 L N DO 1 K 1 N POLY POLY
  • java.util.MissingResourceException:找不到基本名称消息的包,区域设置 en_US

    我是 JSF 的新手 正在尝试这段代码 这是我的 faces config xml
  • 如何动态更新Nifi中的variable.registry.properties?

    变量注册表属性是 Nifi 添加的一项功能 旨在促进软件开发生命周期 这意味着您可以在单独的开发环境中开发流程 并利用 nifi variable registry properties 属性中指定的自定义属性文件以及表达式语言来使用处理器
  • 如何对过滤后的 html 表求和?

    我有一个 HTML 表 我可以使用 jquery 过滤它 在表格的底部 我想要一个 总计 行 它将显示的所有值相加 总计 行中显示的总和应该是显示的所有行的总和 即不考虑隐藏行 我尝试添加一个条件 例如使求和取决于行的显示样式 但这没有成功
  • 为什么当 args 是序列时 subprocess.Popen 不起作用?

    当 args 参数作为序列给出时 我遇到了 subprocess Popen 问题 例如 import subprocess maildir home support Maildir 这有效 它打印 home support Maildir
  • 使用“optparse”模拟 Python 脚本的命令行参数?

    我想使用的 Python 脚本 称为snakefood http furius ca snakefood doc snakefood doc html 通常从命令行运行并采用命令行参数 例如 sfood path to my project
  • 如何指定 unicode 字符范围

    如何指定 Unicode 字符范围 空格 到 u00D7FF 我有一个正则表达式 例如r u0020 u00D7FF 并且它不会编译说这是一个糟糕的范围 我是 Unicode 正则表达式的新手 所以以前没有遇到过这个问题 有没有办法让这个编
  • swift 为 NSStream 创建字节缓冲区持有者

    in the Ray Wenderlich 套接字教程 http www raywenderlich com 3932 networking tutorial for ios how to create a socket based iph
  • Selenium 在 -browserSessionReuse 模式下启动新浏览器

    我正在尝试 browserSessionReuse Selenium 模式来加速我的测试 但我注意到了一个奇怪的行为 这种模式的目的是避免在测试之间浪费时间打开浏览器 这就是它的工作原理 但并非总是如此 如果我连续运行测试 它们就会在同一个
  • 禁用 VS 代码中的警告

    在此输入图像描述 https i stack imgur com KVDnO png 当我点击禁用 工作区 错误是 无法禁用扩展 ESLint 扩展 Node js 扩展包 依赖于此 还有什么其他方法可以消除反应本机错误 你需要定义 esl
  • ggplot 在函数中不起作用,以字符串形式传入变量名

    我有以下简单的功能 但它的 ggplot 命令不起作用 当从命令行给出该命令时 该命令可以正常工作 gt testfn lt function gdf first second library ggplot2 print ggplot gd
  • 包含 symfony2 的文件

    我正在使用 google Drive api 在 symfony2 中进行捆绑 我在 Utils 文件夹中有一个类 Authentication 它与 google 中的文件 我放入完全相同的文件夹中 进行交互 我想将这些文件包含在我的 A
  • 在 B 列中为 A 列中的相同值选择最小值 excel?

    我想得到例如第 1 列中相同值的第 2 列中的最小值或最大值 在我的示例中 我希望值 A 列 1 的列 2 的最大值为 18 而 B 的最大值为 27 我尝试过使用数组函数 但无法使其正常工作 敬请期待任何提示或解决方案 Example C
  • 如何从 web 应用程序运行量角器?

    我想运行一些量角器测试 针对 angularApp 为此 我创建了一个用户界面 提示用户输入脚本文件 然后我需要以某种方式让量角器启动并运行测试 我有哪些选择来实现这一目标 您可以将文件传递到后端 并保存它 然后后端像平常一样执行测试pro
  • 有没有办法在 IE 中获取边框半径和渐变背景?

    我想知道是否有任何使用 javascript 或其他方法让 IE 显示边框半径或渐变背景的解决方法 我在寻找在 IE9 中使用 渐变和边框半径 的修复时遇到了这个问题 是的 虽然您现在可以在 IE9 中同时使用两者 但遗憾的是您不能同时使用
  • 使用 Vector 的 SIMD 向量化 C# 代码运行速度比经典循环慢

    我看过几篇文章描述了如何Vector
  • 递归重命名对象键

    我有一个递归函数来重命名对象的键名称 但我无法弄清楚如何重命名其中 2 个键 问题键是对象 我认为问题在于我正在检查对象类型 但此时如何重命名密钥 实际的数组非常大 但下面是一个缩小版本 任何帮助表示赞赏 var keys short ch