1

I've a json string that I've turned into an object with parseJSON (where #get_my_json_data is a textarea to enter json)

var data = jQuery.parseJSON( $("#get_my_json_data").val() );

cool, I've now got an object to see the whole structure.

What I need to do is to alter the KEY of one node. BUT.. I don't know what it is (so can't just do a stringify and search/replace). I DO know the exact position that it'll be...

Here's a sample structure or the json in the textarea.

{
"MasterData": {
    "|-|-|ID|-|-|": {
        "menu": {
            "Tabs": [
                {
                    "Name": "Home",
                    "TabText": "Home"
                },
.........

I need to find the KEY of the second item, in this example, it's: '|-|-|ID|-|-|'

When they edit again, it'll be different. SO how on earth can I update the node key AFTER MasterData and write the whole thing?

I've tried an $.each loop but it just keeps killing the whole 'array'

---- UPDATE ---

I ended up doing this and it worked great!

    var data = jQuery.parseJSON( $("#get_my_json_data").val() );
    var keys = Object.keys( data.MasterData );
    data.MasterData[$(this).val()] = data.ConteMasterDatatData[keys[0]];
    delete data.MasterData[keys[0]]; 
    $("#get_my_json_data").val(JSON.stringify(data));
Beertastic
  • 691
  • 1
  • 9
  • 27
  • Possible duplicate of [Javascript: Getting the first index of an object](http://stackoverflow.com/questions/909003/javascript-getting-the-first-index-of-an-object) – blgt Mar 15 '16 at 15:50
  • Have you tried to loop through the properties of data.MasterData using Object.getOwnPropertyNames()? – krani Mar 15 '16 at 16:02

1 Answers1

1

Soo if i understood what you want, you want to replace the property name in the parsed object.

Try this:

//Get the keys
var innerkeys = Object.keys(myObject.MasterData);

//Create a property with the information from the first key
myObject["myNewKey"] = myObject.MasterData[innerkeys[0]];

//Delete old property
delete myObject.MasterData[innerkeys[0]];

If you parse the object to json it should be as you expected (not tested)

Information obtained from:

how-to-list-the-properties-of-a-javascript-object

how-do-i-remove-a-property-from-a-javascript-object

Community
  • 1
  • 1
Sílvio N.
  • 361
  • 2
  • 13