Home > Blockchain >  Changing properties in JSON data
Changing properties in JSON data

Time:06-24

how can I change the "ABC" field in the code below?

 var data = {ABC:{key:'dynamic_key',value:'dynamic_value'}}

Normally, I can give the value I want by saying data.ABC.key, but what I really want is to go as data.CCC instead of data.ABC, so I just want to change the ABC name.

CodePudding user response:

Re-assign the inner object to the new outer object key, then delete the previous.

 var data = {ABC:{key:'dynamic_key',value:'dynamic_value'}}
 
 data.CCC = {...data.ABC}
 delete data.ABC
 
 console.log(data)


That also could be (without using delete)

var data = {ABC:{key:'dynamic_key',value:'dynamic_value'}}

data = {CCC: data.ABC}
console.log(data)


EDIT... It you want to use a string from a variable to set the new key, use the bracket notation:

var data = {ABC:{key:'dynamic_key',value:'dynamic_value'}}
var newKey="CAR"

data[newKey] = data.ABC
delete data.ABC
console.log(data)

CodePudding user response:

data.CCC = data.ABC // on object create new key name. Assign old value to this

delete data.ABC //delete object with old key name

output:

{ 
  "CCC":
    {
       "key": "dynamic_key",
       "value": "dynamic_value"
    }
}
  • Related