-4

I am having trouble renaming the key of an object which is inside the array and not only this the name of the is empty as shown below

    {
   "success": true,
    "data": [
        {
            "": "abc123abc"
        }
            ]
    }

If I want to give the name to the key, how would I be able to do that in Node Js?

Like If want to give a key name like this shown below

    {
    "success": true,
    "data": [
        {
            "application_num": "abc123abc"
        }
    ]
}
  • I have voted to close this as no attempt to show debugging procedure has been demonstrated (the "what have you tried?" factor) Also, I don't understand what is meant by "and not only this the name of the is empty as shown below" (although it's clear it's something about the empty string as property name). This is JavaScript 101, I don't think SO is a first response service. Please do a Web search for "JavaScript tutorial". – Armen Michaeli Oct 29 '21 at 10:49
  • Does this answer your question? [JavaScript: Object Rename Key](https://stackoverflow.com/questions/4647817/javascript-object-rename-key) – pilchard Oct 29 '21 at 10:53

2 Answers2

0

There are two components to solving this issue - referencing the item with an empty name, and renaming it.

To reference any property, even with special characters or in this case an empty string, you can specify the property name as a string in square brackets like so:

data["my property with spaces"]
data[""]

Now that we can reference the empty property name, we now need to rename it. This can be achieved by deleting the original property and creating a new one with the same value. You can delete the property with the delete keyword, as follows

delete data[""]

Here is the complete final answer, which stores the value in a temporary variable, deletes the property you don't want, and assigns the stored value to a new different property name:

const data = {
   "success": true,
    "data": [
        {
            "": "abc123abc"
        }
            ]
    }
const dataObjectToModify = data.data[0]
const originalPropertyValue = dataObjectToModify[""]
delete dataObjectToModify[""]
dataObjectToModify["application_num"] = originalPropertyValue
William Forty
  • 212
  • 1
  • 6
0
a = {
   "success": true,
    "data": [
        {
            "": "abc123abc"
        }
            ]
    }

//{
//    "success": true,
//    "data": [
//        {
//            "application_num": "abc123abc"
//        }
//    ]
//}
//--------------------------------

a["data"][0] = {"application_num" : "abc123abc"}

//{
//    "success": true,
//    "data": [
//        {
//            "application_num": "abc123abc"
//        }
//    ]
//}

Anuraag Barde
  • 399
  • 3
  • 9