I'm attempting to write a function which updates a json key value if an attempt is made to add a new key with same name
So in fiddle - http://jsfiddle.net/adrianjsfiddlenetuser/C6Ssa/57/
When the button "Add" is clicked the jSon array toUpdate should be updated :
name: "addThis2",
id : 10
should become
name: "addThis2",
id : 11
This is not occuring ?
Sample JSON :
{
"toAdd": [
{
"name": "addThis",
"id": 10
}
],
"toRemove": [
{
"name": "removeThis"
}
]
}
function updateKeyVal() {
$.each(toUpdate, function(i,e) {
$.each(e, function(j, f) {
if (f.name===valToCheck) f.id=11;
});
});
}
You should change the index of array like folowing:
var toUpdate = {
toAdd: [],
toRemove: []
};
toUpdate.toAdd[0].push({
name: "addThis1",
id: 10
});
toUpdate.toRemove[0].push({
name: "removeThis1"
});
toUpdate.toAdd[1].push({
name: "addThis2",
id: 10
});
toUpdate.toRemove[1].push({
name: "removeThis2"
});
Then you can try
$.each(toUpdate, function(index, data) {
$.each(data, function(key, val) { // here this refer to toAdd, toRemove..
console.log(key); // here this point key of object like name, id ...
console.log(val[key]); // output: addThis, addThis, removeThis
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.