Best way to replace the key in json object

Best way to replace the key in json object

JSON (JavaScript Object Notation, JS Object Notation) is a lightweight data exchange format. It is based on a subset of ECMAScript (js specification developed by the European Computer Association) and uses a text format that is completely independent of the programming language to store and represent data. The simplicity and clear hierarchical structure make JSON an ideal data exchange language. It is easy for humans to read and write, and also easy for machines to parse and generate, and can effectively improve network transmission efficiency.

When you see the title, you might wonder, is such a simple question worth exploring? If I have a json object, I can do it with just a few lines of code:

var obj = {
    "_id": "5078c3a803ff4197dc81fbfb",
    "email": "[email protected]",
    "image": "some_image_url",
    "name": "Name 1"
};

var new_key = "id";
var old_key = "_id";

obj[new_key] = obj[old_key];
delete obj[old_key];

Yes, that's right! The above code does the job just fine, replacing "_id" with "id" in the obj object.

In most cases this approach will not cause any problems, however, if you need to serialize the obj object into a document and compare the differences, you will see problems.

// Modify the previous obj
{
    "_id": "5078c3a803ff4197dc81fbfb",
    "email": "[email protected]",
    "image": "some_image_url",
    "name": "Name 1"
}

// obj after modification 
// JSON.stringify(obj, null, "\t")
{
    "email": "[email protected]",
    "image": "some_image_url",
    "name": "Name 1",
    "id": "5078c3a803ff4197dc81fbfb"
}

The newly added key is placed at the end by default, and because we deleted the previous key during the replacement process, the obj after serialization is significantly different from the previous obj.

So how can we ensure that key replacement is achieved with minimal differences? Here are some methods I found:

Object.prototype.renameProperty = function (oldName, newName) {
     // Do nothing if the names are the same
     if (oldName === newName) {
         return this;
     }
    // Check for the old property name to avoid a ReferenceError in strict mode.
    if (this.hasOwnProperty(oldName)) {
        this[newName] = this[oldName];
        delete this[oldName];
    }
    return this;
};
function renameKeys(obj, newKeys) {
  const keyValues ​​= Object.keys(obj).map(key => {
    const newKey = newKeys[key] || key;
    return { [newKey]: obj[key] };
  });
  return Object.assign({}, ...keyValues);
}


const obj = { a: "1", b: "2" };
const newKeys = { a: "A", c: "C" };
const renamedObj = renameKeys(obj, newKeys);
console.log(renamedObj);
// {A:"1", b:"2"}
// Using lodash's _.mapKeys() function var user = {
  name: "Andrew",
  id: 25,
  reported: false
};

var renamed = _.mapKeys(user, function(value, key) {
  return key + "_" + user.id;
});

console.log(renamed);
var str = JSON.stringify(object);
str = str.replace(/oldKey/g, 'newKey');
str = str.replace(/oldKey2/g, 'newKey2');

object = JSON.parse(str);
function renameObjectKey(oldObj, oldName, newName) {
    const newObj = {};

    Object.keys(oldObj).forEach(key => {
        const value = oldObj[key];

        if (key === oldName) {
            newObj[newName] = value;
        } else {
            newObj[key] = value;
        }
    });

    return newObj;
}
data = {key1: "value1", key2: "value2", key3: "value3"}; 

keyMap = {key1: "firstkey", key2: "secondkey", key3: "thirdkey"};

mappedData = Object.keys(keyMap).reduce((obj,k) => Object.assign(obj, { [keyMap[k]]: data[k] }),{});

console.log(mappedData);

Some of the examples above can meet our requirements, and some of them are basically equivalent to the code given at the beginning of this article (with only slight differences in execution efficiency). But all of these examples, without exception, fail to meet the following two requirements at the same time:

Keep the order of the keys to be replaced in the original JSON object. This ensures that the order of keys in the string output after JSON.stringify() is executed is consistent with the original JSON object. Modify the original JSON object instead of returning a new JSON object. In some cases, we need to modify the sub-elements of a complex JSON object. If a new JSON object is returned after the modification, there is no guarantee that the new object will be reflected in the original JSON object. For example, jspath is a javascript library that can find child elements in a given json object through a domain-specific language (DSL). With the following code, we can easily find the elements in the automobiles property of the obj object where maker === "Honda" and year > 2009.

var obj = {
    "automobiles" : [
        { "maker" : "Nissan", "model" : "Teana", "year" : 2011 },
        { "maker" : "Honda", "model" : "Jazz", "year" : 2010 },
        { "maker" : "Honda", "model" : "Civic", "year" : 2007 },
        { "maker" : "Toyota", "model" : "Yaris", "year" : 2008 },
        { "maker" : "Honda", "model" : "Accord", "year" : 2011 }
    ],
    "motorcycles" : [{ "maker" : "Honda", "model" : "ST1300", "year" : 2012 }]
};

var res = JSPath.apply('.automobiles{.maker === "Honda" && .year > 2009}', obj);

// res: [{ "maker" : "Honda", "model" : "Jazz", "year" : 2010 }, { "maker" : "Honda", "model" : "Accord", "year" : 2011 }]

Note that the res object returned here is part of the obj object, which means that any subsequent changes made to the res object will be reflected in the obj object. If we replace some keys in res and return a new json object, then this modification will not be reflected in the obj object.

Basic idea: Since the newly added key will be ranked last by default, simply traverse all the keys of the JSON object, and then replace the key one by one with a temporary name, and then replace the temporary name back. During this process, if a key that really needs to be replaced is encountered, no secondary replacement will be performed. Here is the specific code:

var obj = {
    "_id": "5078c3a803ff4197dc81fbfb",
    "email": "[email protected]",
    "image": "some_image_url",
    "name": "Name 1"
};

var new_key = "id";
var old_key = "_id";

Object.keys(obj).forEach(key => {
    if (key === old_key) {
        obj[new_key] = obj[key];
        delete obj[key];
    } else {
        obj[`_${key}`] = obj[key];
        delete obj[key];

        obj[`${key}`] = obj[`_${key}`];
        delete obj[`_${key}`];
    }
});

The completed effect is as follows:

Of course, if you consider universality, you may need to recursively traverse the given JSON object. The above code only gives an idea. Considering the execution efficiency and security, this is not the best solution. We can gradually improve it in actual use.

The above is the details of the best solution for replacing the key in the JSON object. For more information about replacing the key in the JSON object, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • C# Example of getting the value of a json object with a dynamic key
  • Analysis of common methods of JS operating json object key and value
  • JavaScript traverses the key of the json object and any js object attribute instance
  • How to traverse all keys of json object and get values ​​according to dynamic keys in js (must read)
  • JS obtains the parameter value in the URL according to the key value and converts the URL parameter into a json object
  • C# implements the method of converting json format into objects and changing keys

<<:  Complete steps to reset the root user password in mysql8

>>:  How to monitor Windows performance on Zabbix

Recommend

Practical TypeScript tips you may not know

Table of contents Preface Function Overloading Ma...

How to split data in MySQL table and database

Table of contents 1. Vertical (longitudinal) slic...

How to check if the firewall is turned off in Linux

1. Service method Check the firewall status: [roo...

How to find and delete duplicate rows in MySQL

Table of contents 1. How to find duplicate rows 2...

Web page experience: Web page color matching

<br />The color of a web page is one of the ...

Analysis of the implementation process of three modes of VMWare network adapter

Three modes Bridged (bridge mode), NAT (network a...

Vue achieves seamless carousel effect

This article shares the specific code of Vue to a...

How to solve the problem of margin overlap

1. First, you need to know what will trigger the v...

Better looking CSS custom styles (title h1 h2 h3)

Rendering Commonly used styles in Blog Garden /*T...

Comprehensive understanding of HTML basic structure

Introduction to HTML HyperText Markup Language: H...

Mysql some complex sql statements (query and delete duplicate rows)

1. Find duplicate rows SELECT * FROM blog_user_re...

Tutorial on installing the unpacked version of mysql5.7 on CentOS 7

1. Unzip the mysql compressed package to the /usr...

CSS Tutorial: CSS Attribute Media Type

One of the most important features of a style she...

Teach you MySQL query optimization analysis tutorial step by step

Preface MySQL is a relational database with stron...