Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want get one specific entry from JSON data array and do some modification

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?

like image 420
Daniel Chen Avatar asked Feb 12 '26 16:02

Daniel Chen


2 Answers

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;
    }
  }
}
like image 191
Jakob Avatar answered Feb 15 '26 06:02

Jakob


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);
}
like image 23
Spiny Norman Avatar answered Feb 15 '26 05:02

Spiny Norman