nilkash
nilkash

Reputation: 7536

Deleting particular data from a json object using JavaScript

I am using titanium for developing Android application. I want to delete some data from json object. My json object given below:

{"feeds":
[
    {"username":"abc","user":"abc","feed":{"description":"dss","id":660,"user_id":1}},
    {"username":"bcd","user":"bcd","feed":{"description":"dddd","id":659,"user_id":1}}
]
}

for receiving json object I used following code

var json = this.responseText;
var json = JSON.parse(json);
json.feeds.splice(0,1);
alert(json.feeds[0]);

I want to delete particular data from json object like json.feeds[0] using JavaScript. I am able to access json.feeds[0] but not able to delete. Is there any way to delete that data from json object using JavaScript?

Upvotes: 0

Views: 5896

Answers (2)

Li0liQ
Li0liQ

Reputation: 11264

You are using splice to properly remove an element from a javascript array:

json.feeds.splice(0,1)

Using the code you've provided it will look like:

(function(){
    var json = {
        "feeds": [
            {"username":"abc","user":"abc","feed":{"description":"dss","id":660,"user_id":1}},
            {"username":"bcd","user":"bcd","feed":{"description":"dddd","id":659,"user_id":1}}
        ]
    };

    json.feeds.splice(0,1);
    console.log(json.feeds); // just to check that "feeds" contains only a single element
})();

Upvotes: 3

Quentin
Quentin

Reputation: 943220

  1. Parse the JSON into a JavaScript data structure
  2. Use splice to remove the elements you don't want from the array
  3. Serialise the JavaScript objects back into JSON

Upvotes: 3

Related Questions