3

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

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}

And send back to server by using

$.post(url, data);

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

Daniel Chen
  • 1,933
  • 5
  • 24
  • 33

3 Answers3

6

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

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

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;
    }
  }
}
Jakob
  • 24,154
  • 8
  • 46
  • 57
  • Thanks @Jakob but my JSON data was got by $.getJOSN(); function, I don't have exact file in this format... I don't know how to make like var result={entries:[...]} – Daniel Chen Dec 07 '10 at 15:54
  • You said that you got data in that format yourself. I just named the variable with the data "result", so that I could use it in a program. I cant loop over something if it doesn't have a name :) – Jakob Dec 07 '10 at 17:03
  • Can't you limit the response to just the data you want returned? – Mudlabs Mar 14 '17 at 10:50
1

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);
}
Spiny Norman
  • 8,277
  • 1
  • 30
  • 55
0

You need to loop through your data. Alternatively you could restructure your JSON:

{"entries":{"UUID1":{"title":"foo", "finished": false }}, {"UUID2":{"title":"bar", "finished":false}}}
sunn0
  • 2,918
  • 1
  • 24
  • 25