javascript 我想从 JSON 数据数组中获取一个特定条目并进行一些修改
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4377220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
I want get one specific entry from JSON data array and do some modification
提问by Daniel Chen
first I got JSON data via web server just like
首先我通过网络服务器获得了 JSON 数据,就像
$.getJSON(url,function(){
//my callback function;
});
And now I've got data as following:
现在我有如下数据:
{entries:[{title:'foo',id:'UUID',finished:null},{title:'bar',id:'UUID',finished:null},{title:'baz',id:'UUID',finished:null}]}
I have to find one specific JSON entry by it's UUID, and after that I need to modify one part for example, make a new json data:
我必须通过它的 UUID 找到一个特定的 JSON 条目,然后我需要修改一个部分,例如,创建一个新的 json 数据:
{title:'foo',id:'UUID',finished:true}
And send back to server by using
并通过使用发送回服务器
$.post(url, data);
I'm totally lost myself with this situation... can anyone help?
在这种情况下我完全迷失了自己......有人可以帮忙吗?
回答by Jakob
Assuming that you've put the data in a variable called result, like this:
假设您已将数据放入名为 的变量中result,如下所示:
var result = {entries:[{title:'foo',id:'UUID',finished:null},{title:'bar',id:'UUID',finished:null},{title:'baz',id:'UUID',finished:null}]}
You could do a for-loop:
你可以做一个for循环:
for ( var i=0; i<result.entries.length; i++ ) {
if (result.entries[i].id == 'the_UUID_you_are_looking_for') {
var entry = result.entries[i]; // "entry" is now the entry you were looking for
// ... do something useful with "entry" here...
}
}
Edit - I've written the full solution below, to further illustrate the idea and avoid misunderstandings:
编辑 - 我在下面写了完整的解决方案,以进一步说明这个想法并避免误解:
// Get data from the server
$.getJSON("url", function(result) {
// Loop through the data returned by the server to find the UUId of interest
for ( var i=0; i<result.entries.length; i++ ) {
if (result.entries[i].id == 'the_UUID_you_are_looking_for') {
var entry = result.entries[i];
// Modifiy the entry as you wish here.
// The question only mentioned setting "finished" to true, so that's
// what I'm doing, but you can change it in any way you want to.
entry.finished = true;
// Post the modified data back to the server and break the loop
$.post("url", result);
break;
}
}
}
回答by Spiny Norman
Try this:
试试这个:
var modified = false, myUuid = 'some uuid';
for (i = 0; i < data.entries.length; i++) {
if (data.entries[i].id === myUuid) {
data.entries[i].finished = true;
modified = true;
break;
}
}
if (modified) {
$.post(url, data);
}
回答by sunn0
You need to loop through your data. Alternatively you could restructure your JSON:
您需要遍历数据。或者,您可以重组您的 JSON:
{"entries":{"UUID1":{"title":"foo", "finished": false }}, {"UUID2":{"title":"bar", "finished":false}}}

