JMA
JMA

Reputation: 994

Editing and removing value in json using jquery

I have this JSON,

{"items":[{"Code":"c101","Desc":"Car"},{"Code":"c341","Desc":"House"}]}

How can I edit the Desc of the item that have a code of c341? How can I delete the item that have a code of c101?

I tried this code but not working,

delete obj.items.Code="c101"

Upvotes: 1

Views: 35

Answers (4)

Webman
Webman

Reputation: 1554

Before you have to find the item by its code and then edit it

var obj = {"items":[{"Code":"c101","Desc":"Car"},{"Code":"c341","Desc":"House"}]};

function getItemByCode(code){

    for(var i in obj.items){
        var item = obj.items[i];
        if(item.Code === code){
            return item;
        };
    };
}

var item = getItemByCode('c341');    

item.Desc = "new desc"

This solution works with IE9+ and others browsers

Upvotes: 0

minitauros
minitauros

Reputation: 2030

Have you tried:

var json_string = '{"items":[{"Code":"c101","Desc":"Car"},{"Code":"c341","Desc":"House"}]}';
var json = JSON.parse(json_string);

if (json && json.items) {
	json.items = json.items.filter((element, i) => {
		if (element.Code) {
			return element.Code != 'c101';
		}
		return true;
	});
}

Upvotes: 0

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67217

For deleting the item with specific id use Array.prototype.findIndex() and splice(),

obj.items.splice(obj.items.findIndex(v => v.Code == "c101"), 1)

For editing use Array.prototype.find(),

var edit = obj.items.find(v => v.Code == "c341")
edit.Code = "asd" //This will affect the item's code in the original array
                  //since `find()` will return the reference not a copy.

Upvotes: 1

mhodges
mhodges

Reputation: 11126

There are probably more efficient solutions out there, but this is the basic idea of what you want to do.

$.each(obj.items, function (index, element){
  if (element.Code === "c101") {
    obj.items.splice(index, 1);
    return false;
  }
});

Upvotes: 0

Related Questions