使用Javascript更新JSON对象 [英] Updating a JSON object using Javascript
本文介绍了使用Javascript更新JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用javascript或Jquery动态更新以下JSON对象?
How can i update the following JSON object dynamically using javascript or Jquery?
var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'},
{'Id':'2','Username':'Steve','FatherName':'Johnson'},
{'Id':'3','Username':'Albert','FatherName':'Einstein'}]
我想将用户名动态更新为'Thomas',其中'Id'为'3'。
I would like to dynamically update the Username to 'Thomas' where the 'Id' is '3'.
我该怎么办?实现这个?
How can I acheive this?
推荐答案
一个简单的JavaScript解决方案:
A plain JavaScript solution:
循环结束它寻找匹配的Id,设置相应的用户名,并在匹配的项目被修改后从循环中 break
:
Loop over it looking for the matching Id, set the corresponding Username, and break
from the loop after the matched item has been modified:
for (var i = 0; i < jsonObj.length; i++) {
if (jsonObj[i].Id === 3) {
jsonObj[i].Username = "Thomas";
break;
}
}
这是包含在函数中的相同内容:
Here's the same thing wrapped in a function:
function setUsername(id, newUsername) {
for (var i = 0; i < jsonObj.length; i++) {
if (jsonObj[i].Id === id) {
jsonObj[i].Username = newUsername;
return;
}
}
}
// Call as
setUsername(3, "Thomas");
这篇关于使用Javascript更新JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文