如何更改 JSON 字符串内的值
我有一个像这样的 JSON string 对象数组。
[{"id":"4","rank":"adm","title":"title 1"},
{"id":"2","rank":"mod","title":"title 2"},
{"id":"5","rank":"das","title":"title 3"},
{"id":"1","rank":"usr","title":"title 4"},
{"id":"3","rank":"ref","title":"title 5"}]
一旦 id 匹配,我想更改它的标题值。因此,如果我的变量 myID 是 5,我想将标题“标题 5”更改为新标题,依此类推。然后我将新的 JSON 数组获取到 $("#rangArray").val(jsonStr);
类似
$.each(jsonStr, function(k,v) {
if (v==myID) {
this.title='new title'; $("#myTextArea").val(jsonStr);
}
});
以下是完整代码。
$('img.delete').click(function() {
var deltid = $(this).attr("id").split('_');
var newID = deltid[1];
var jsonStr = JSON.stringify(myArray);
$.each(jsonStr, function(k,v) {
if (v==newID) {
// how to change the title
jsonStr[k].title = 'new title';
alert(jsonStr);
$("#rangArray").val(jsonStr);
}
});
});
上面的方法不起作用。有什么帮助吗?
I have a JSON string array of objects like this.
[{"id":"4","rank":"adm","title":"title 1"},
{"id":"2","rank":"mod","title":"title 2"},
{"id":"5","rank":"das","title":"title 3"},
{"id":"1","rank":"usr","title":"title 4"},
{"id":"3","rank":"ref","title":"title 5"}]
I want to change the title value of it, once the id is matching. So if my variable myID is 5, I want to change the title "title 5" to new title, and so on. And then I get the new JSON array to $("#rangArray").val(jsonStr);
Something like
$.each(jsonStr, function(k,v) {
if (v==myID) {
this.title='new title'; $("#myTextArea").val(jsonStr);
}
});
Here is the full code.
$('img.delete').click(function() {
var deltid = $(this).attr("id").split('_');
var newID = deltid[1];
var jsonStr = JSON.stringify(myArray);
$.each(jsonStr, function(k,v) {
if (v==newID) {
// how to change the title
jsonStr[k].title = 'new title';
alert(jsonStr);
$("#rangArray").val(jsonStr);
}
});
});
The above is not working. Any help please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
现场演示: http://jsfiddle.net/CVvW4/1/< /a>
完整片段(已实现我的代码):
Try this:
Live demo: http://jsfiddle.net/CVvW4/1/
Full snipped (with my code implemented):
您应该执行
jsonStr[v].title = "new title";
您的
jsonStr
是一个对象数组。You should be doing
jsonStr[v].title = "new title";
Your
jsonStr
is an array of objects.尝试使用 jsonStr[k].title = 'new title';
Try using
jsonStr[k].title = 'new title';