Kanish Mishra
Kanish Mishra

Reputation: 23

Add and remove json data into object in object dynamically

i want to create a json object that store multiple object like this

    {
  "info": [
    {
      "id": "9861230",
      "LastPing": "hey",
      "LastPingTime": "12:30",
      "Message": [
        {
          "s_Message": "hello",
          "s_time": "01:30",
          "r_Message": "hii",
          "r_time": "01:31"
        }
      ]
    },
    {
      "id": "982121",
      "LastPing": "hey",
      "LastPingTime": "12:30",
      "Message": [
        {
          "s_Message": "hello",
          "s_time": "01:30",
          "r_Message": "hii",
          "r_time": "01:31"
        }
      ]
    }
  ]
}

i want to create such type of json data dynamically, things that i want. suppose i am ping to this id = 9861230 so it will modify and add new message array in this id = 9861230 object and if there is not related id present on object then it will add new object that will contain such type of info that i have entered.

Upvotes: 0

Views: 119

Answers (1)

varun
varun

Reputation: 662

Use id as key

obj = {
    "982121" : {
       "LastPing":"hey",
       "LastPingTime":"12:30",
       "Message":[
         {
           "s_Message":"hello",
           "s_time":"01:30",
           "r_Message":"hii",
           "r_time":"01:31"
         }
        ]
    }
}

This way you can easily add message to message array in a particular id without traversing the info array and find the object with a particular id.

if (obj[id]) {
    obj[id].messages.push(message);
}
else {
   obj[id] = {
       messages : []
   };
   obj[id].messages.push(message);
}

Upvotes: 1

Related Questions