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

11,994

Solution 1

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

Solution 2

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);
}
Share:
11,994
Daniel Chen
Author by

Daniel Chen

Updated on June 22, 2022

Comments

  • Daniel Chen
    Daniel Chen almost 2 years

    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?