user3578827
user3578827

Reputation: 1

how to add and remove key from json dynamically

I need to add and remove key from json dynamically with true or false, i'm doing code for rent car site with jquery mobile and want to make choosen car unavailable, by changing the available to ture or false when the user choose it.

var davcarlist = [{
    "model": "Fiat",
    "number": 111111,
    "gear": "Manual",
    "available": true
}, {
    "model": "Ford",
    "number": 222222,
    "gear": "Manual",
    "available": true
}, {
    "model": "Mazda",
    "number": 333333,
    "gear": "Auto",
    "available": true
}, {
    "model": "Toyota",
    "number": 444444,
    "gear": "Auto",
    "available": true
}, {
    "model": "Audi",
    "number": 555555,
    "gear": "Auto",
    "available": true
}];
var dvdcarlist = JSON.stringify(davcarlist);
localStorage.setItem('someData', dvdcarlist);

Upvotes: 0

Views: 99

Answers (1)

Joseph
Joseph

Reputation: 119867

To change the value of available, you do:

davcarlist[i].available = false;

To remove an item from the array, yo do:

davcarlist.splice(i,1);

Where i is the index of that item in the array. For instance, when i is 0, we're referring to the Fiat.

By the way, "JSON" is a string, a serialized version of a Javascript object. What you have there is an array.

Upvotes: 1

Related Questions