我想从JSON数据数组中获取一个特定条目并进行一些修改 [英] I want get one specific entry from JSON data array and do some modification

查看:107
本文介绍了我想从JSON数据数组中获取一个特定条目并进行一些修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我像通过网络服务器一样获得JSON数据

first I got JSON data via web server just like

$.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}]}

我必须通过它的UUID找到一个特定的JSON条目,然后需要修改一个部分,例如,制作一个新的json数据:

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:

{title:'foo',id:'UUID',finished:true}

并使用发送回服务器

$.post(url, data);

在这种情况下,我完全迷失了自己...任何人都可以帮忙吗?

I'm totally lost myself with this situation... can anyone help?

推荐答案

假定您已将数据放入名为result的变量中,如下所示:

Assuming that you've put the data in a variable called result, like this:

var result = {entries:[{title:'foo',id:'UUID',finished:null},{title:'bar',id:'UUID',finished:null},{title:'baz',id:'UUID',finished:null}]}

您可以进行for循环:

You could do a for-loop:

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...
  }
}

编辑-我在下面编写了完整的解决方案,以进一步说明该想法并避免误解:

// 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;
    }
  }
}

这篇关于我想从JSON数据数组中获取一个特定条目并进行一些修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆