Wednesday, 5 February 2020

How to rename key of an Object

JavaScriptRename KeyObject

In this article we are going to discuss about how to rename a key. Let us take an example of a simple object first.


let sampleObj = {
    "name": "Angular",
    "version": "8"
};

for (const k in sampleObj) {
    if (k === "name") {
        sampleObj["newKeyName"] = sampleObj[k];
        delete sampleObj[k];
    }
}

Here we deleted the key and added new one with out changing its value. End result is equal to rename the key.

Here we checked directly key === "name", you can add your own conditions. (indexOf(k), etc) according to your requirements.

Output

Now check with another example.


let data = [{
    "name": "Angular",
    "version": "8"
}, {
    "name": "React",
    "version": "6"
}, {
    "name": "Backbone",
    "version": "7"
}];

data.forEach((obj) => {
    for (const k in obj) {
        if (k === "name") {
            obj["newKeyname"] = obj[k];
            delete obj[k]
        }
    }
})



Here we are looping over array of object and renaming the key.

In this article we have discussed about how to rename key of an object.

Related Info

1. File/image upload and send data to backend - Angular

2. Show preview image while uploading - Angular

No comments :

Post a comment