I want to get one specific record from a JSON data array and make some changes

first i got json data via web server like

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

And now I have the data as follows:

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

I need to find one specific JSON entry using the UUID, and after that I need to, for example, change one part, create new json data:

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

And send back to server using

$.post(url, data);

I completely lost myself in this situation ... can anyone help?

+3
source share
3 answers

Assuming you put the data in a variable with a name result, for example:

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

You can 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;
    }
  }
}
+6

:

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);
}
+1

You need to scroll through the data. Alternatively, you can rebuild your JSON:

{"entries":{"UUID1":{"title":"foo", "finished": false }}, {"UUID2":{"title":"bar", "finished":false}}}
0
source

Source: https://habr.com/ru/post/1778965/


All Articles