javascript - 我想从 JSON 数据数组中获取一个特定条目并进行一些修改

标签 javascript jquery ajax json api

首先我通过网络服务器获取 JSON 数据,就像

$.getJSON(url,function(){
//my callback function;
});

现在我得到如下数据:

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

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

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

并通过使用发送回服务器

$.post(url, data);

在这种情况下我完全迷失了自己......有人能帮忙吗?

最佳答案

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

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

你可以做一个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...
  }
}

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

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

关于javascript - 我想从 JSON 数据数组中获取一个特定条目并进行一些修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4377220/

相关文章:

javascript - jquery如何从div测验按钮中删除元素

jquery - ajax调用不支持请求方法 'POST'

javascript - 如何使用 JavaScript 将输入提交元素转换为按钮元素?

javascript - 如何在 jQuery Ajax 调用后管理重定向请求

java - byte[] 到 Wicket 中的 iresourcestream

javascript - 在JS中加载本地json文件

javascript - Webfont 性能 - webfontloader 与预加载

javascript - rails 中的 jquery : changing color of textbox dynamically

javascript - AJAX 带滚动条的水平滚动

javascript - Sql 语句 JavaScript