有效地重命名/重新映射结构阵列内的JavaScript / JSON对象键 [英] Efficiently rename/re-map javascript/json object keys within structured array

查看:91
本文介绍了有效地重命名/重新映射结构阵列内的JavaScript / JSON对象键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢所以一些结构化的JSON数据。让我们假设这是可以互换的,通过<一href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse\"><$c$c>JSON.parse():

I have some structured JSON data like so. Let's assume this is interchangeable, via JSON.parse():

[
    {
        "title": "pineapple",
        "uid": "ab982d34c98f"
    },
    {
        "title": "carrots",
        "uid": "6f12e6ba45ec"
    }
]

我需要它看起来像这样,重新映射标题名称 UID ID 的结果是:

[
    {
        "name": "pineapple",
        "id": "ab982d34c98f"
    },
    {
        "name": "carrots",
        "id": "6f12e6ba45ec"
    }
]

做的最明显的方法是这样的:

The most obvious way of doing it is like this:

str = '[{"title": "pineapple","uid": "ab982d34c98f"},{"title": "carrots", "uid": "6f12e6ba45ec"}]';

var arr = JSON.parse(str);
for (var i = 0; i<arr.length; i++) {
    arr[i].name = arr[i].title;
    arr[i].id = arr[i].uid;
    delete arr[i].title;
    delete arr[i].uid;
}

小提琴

...或使用更复杂的东西(虽然的的更有效)喜欢的这个

...or using something more complex (albeit not more efficient) like this.

这是所有罚款和花花公子,但如果有数组200,000对象?这是一个很大的处理开销。

This is all fine and dandy, but what if there were 200,000 objects in the array? This is a lot of processing overhead.

有没有重新映射键名更有效的方法?可能不通过对象的整个数组循环?如果你的方法更有效,请提供证明/引用。

推荐答案

正如我在评论中已经提到的,如果你能做出关于对象的值的某些假设,你可以使用一个普通的前pression更换按键,例如:

As I already mentioned in the comments, if you can make certain assumptions about the values of the objects, you could use a regular expression to replace the keys, for example:

str = str.replace(/"title":/g, '"name":');

这并不是因为干净,但它可能会更快地完成工作。

It's not as "clean", but it might get the job done faster.

如果你总得去解析JSON,一个更有条理的方法是<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse\">pass一个的齐磊的函数 JSON.parse ,你可能能够避免阵列上的额外的通行证。这可能取决于引擎如何落实 JSON.parse 虽然(也许他们首先分析整个字符串,然后进行第二次飞掠与齐磊功能,在这种情况下,你不会得到任何好处)。

If you have to parse the JSON anyway, a more structured approach would be to pass a reviver function to JSON.parse and you might be able to avoid an additional pass over the array. This probably depends on how engine implement JSON.parse though (maybe they parse the whole string first and then make a second pass with the reviver function, in which case you wouldn't get any advantage).

var arr = JSON.parse(str, function(prop, value) {
   switch(prop) {
     case "title":
        this.name = value;
        return;
     case "uid":
        this.id = value;
        return;
     default:
        return value;
   }
});


基准,使用下面的Node.js的脚本来测试3次:


Benchmarks, using the Node.js script below to test 3 times:

1389822740739: Beginning regex rename test
1389822740761: Regex rename complete
// 22ms, 22ms, 21ms
1389822740762: Beginning parse and remap in for loop test
1389822740831: For loop remap complete
// 69ms, 68ms, 68ms
1389822740831: Beginning reviver function test
1389822740893: Reviver function complete
// 62ms, 61ms, 60ms

它显示为如果正则表达式(在这种情况下)是最有效的,但<一href=\"http://stackoverflow.com/questions/408570/regular-ex$p$pssion-to-parse-an-array-of-json-objects\">be小心试图用常规的前pressions 来解析JSON的时候。

It appears as if the regex (in this case) is the most efficient, but be careful when trying to parse JSON with regular expressions.

测试脚本,装载100230线OP的样品JSON的:

Test script, loading 100,230 lines of the OP's sample JSON:

fs = require('fs');
fs.readFile('test.json', 'utf8', function (err, data) {
    if (err) {
        return console.log(err);
    }
    console.log(new Date().getTime() + ": Beginning regex rename test");
    var str = data.replace(/"title":/g, '"name":');
    str = str.replace(/"uid":/g, '"id":');
    JSON.parse(str);
    console.log(new Date().getTime() + ": Regex rename complete");
    console.log(new Date().getTime() + ": Beginning parse and remap in for loop test");
    var arr = JSON.parse(data);
    for (var i = 0; i < arr.length; i++) {
        arr[i].name = arr[i].title;
        arr[i].id = arr[i].uid;
        delete arr[i].title;
        delete arr[i].uid;
    }
    console.log(new Date().getTime() + ": For loop remap complete");
    console.log(new Date().getTime() + ": Beginning reviver function test");
    var arr = JSON.parse(data, function (prop, value) {
        switch (prop) {
            case "title":
                this.name = value;
                return;
            case "uid":
                this.id = value;
                return;
            default:
                return value;
        }
    });
    console.log(new Date().getTime() + ": Reviver function complete");
});

这篇关于有效地重命名/重新映射结构阵列内的JavaScript / JSON对象键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆