Skip to content
Advertisement

Remove and Modify key from object

I have following object

{
  "tenant": "bclient",
  "name": "somename",
  "published_at": "2010-01-01T12:00:00.000Z",
  "payload": {
    "id": "04d02325-f4ea-4a7b-bfeb-2ff74a0e1a0d",
    "external_id": "849849889",
    "created_at": "2018-07-06T11:56:34.712Z",
    "placed_at": "2018-07-06T12:06:25.989Z",
    "associate_id": "121edewcsecsdc",
    "associate_email": "abc@example.com",
    "channel_type": "web",
    "channel": "webshop-123",
    "is_exchange": false,
    "customer_email": "johndoe@example.com",
    "customer_id": "84ca4scac9aca98s",
    "external_customer_id": "CUST123423",
    "is_historical": true,
  }
}

I want to remove is_exchange and replace value of created_at to “2021-03-23” and get back the json representation of the object

I tried like

var data= JSON.parse(myjsonobj) 
delete data['payload']['external_id']; 

which is working but

data.payload.created_at = '2021-03-23' 

is not working

const myjsonobj = `{
      "tenant": "bclient",
      "name": "somename",
      "published_at": "2010-01-01T12:00:00.000Z",
      "payload": {
        "id": "04d02325-f4ea-4a7b-bfeb-2ff74a0e1a0d",
        "external_id": "849849889",
        "created_at": "2018-07-06T11:56:34.712Z",
        "placed_at": "2018-07-06T12:06:25.989Z",
        "associate_id": "121edewcsecsdc",
        "associate_email": "abc@example.com",
        "channel_type": "web",
        "channel": "webshop-123",
        "is_exchange": false,
        "customer_email": "johndoe@example.com",
        "customer_id": "84ca4scac9aca98s",
        "external_customer_id": "CUST123423",
        "is_historical": true
      }
    }`

var data = JSON.parse(myjsonobj)
delete data['payload']['external_id'];

data.payload.created_at = '2021-03-23'

console.log(data)

Advertisement

Answer

To remove a value from an object use the delete method. So, you could do delete obj.payload.is_exchange. And to change a value, just use the = operator. obj.payload.created_at = "2021-03-23".

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement