简体   繁体   中英

Finding properties in a javascript object

I have a javascript object, which I have received from a JSONP file.

The object contains multiple "options" and "results", which are used to adjust the html on the page when a user clicks.

Right now, I am able to check if the HTML string (inserted via json reference) exists in the json file. What I want to do is take that string, find the next "result" or "option" in the json file, and then return that "option" or "result" value so I can use it to change the html...

How do I do that? I've been trying the .indexOf method to find the current index but that doesn't really help me find a specific property like an "option".

This is the code I'm using to iterate through the JSONP file and find if the current string exists.

$.ajax({
    url: "http://www.myurl.com/jsonp.php",
    type: "GET",
    dataType: "jsonp",
    jsonpCallback: "otmjsonp",
    async: false,
    success: function (JSON) {
        $(".result").on("click", function () {
            var currentResult = $(this).text(); //.result is the line of HTML the user has clicked
            for (var playerSelection in JSON) {
                if (JSON.hasOwnProperty(playerSelection)) {
                    if (JSON[playerSelection] === currentResult) {
                        alert("this selection exists in the JSON");
                    }
                }
            }
        })
    }
});

And here is a VERY simple version of the large JSONP file:

otmjsonp({
"situation1" : "Your opponent is trying to tackle you", "playerPrompt1" : "What will you do first?", 

"option1" : "avoid him",

    "result1" : "he tackles you",

        "situation2" : "you were tackled", "playerPrompt2" : "Your opponent begins to slow down",

        "option2" : "chase after him",
            "result2" : "you caught up",
)}

etc. etc.

Even vague ideas/directions would be appreciated as I'm completely stuck.

If you re-structure your JSON to nest the options/result inside the respective parent it becomes easy to get all the possible options. You would need to change your code to this:

$.ajax({
url: "http://www.myurl.com/jsonp.php",
type: "GET",
dataType: "jsonp",
jsonpCallback: "otmjsonp",
async: false,
success: function (JSON) {
    $(".result").on("click", function () {
        var currentResult = $(this).text(); //.result is the line of HTML the user has clicked

     if (JSON.hasOwnProperty(playerSelection)) {
      for (var outcome in JSON[playerSelection]) {
       if (JSON[playerselection].hasOwnProperty(outcome)) {
        alert("This is the next outcome " + JSON[playerSelection][outcome]);
       }
      }
     }
   })
  }
});

I would suggest thinking through and organizing your JSON structure before progressing much further. Organized and logical JSON will make the Javascript easier. For this situation -- as much as I can glean from the description and example -- I think a JSON structure that would make logical sense and prove useful in later Javascript might look something like this:

{
  'situations': [
    {
      'description': 'Your opponent is trying to tackle you.',
      'prompt': 'What will you do?',
      'options': [
        {
          'action': 'Avoid him.',
          'result': 'He tackles you.'
        },
        { /* another option (an action plus a result) */ }
      ]
    },
    { /* another situation (a description, a prompt, and an array of options) */ }
  ]
}

I know this isn't a complete answer to your problem, but I think it would be a good place to start re-thinking your approach.

Part of the issue here is how you've coupled your UI with your data initialization. What I think you really want to do is to separate out the JSON request getting the data from the handling of the click.

$(function() {

  var setupHTML, 
      handleClick,
      updateHTML,
      originalData,
      resultData;

  updateHTML = function(JSON) {
    // Add or activate the html the person is clicking
    $('.result').text()
  };

  handleClick = function(e) {
    var currChoice = $(e.target).text();

    if (resultData === undefined) {
      e.stopPropagation();
      e.preventDefault();
      return;
    }

    for (var ps in resultData) {
      if (resultData.hasOwnProperty(ps) && resultData[ps] === currChoice) {
        resultData = resultData[ps];
        updateHTML(resultData);
      }
    }
  }

  $('.result').on('click', handleClick)


  $.ajax({
    url: "http://www.myurl.com/jsonp.php",
    type: "GET",
    dataType: "jsonp",
    jsonpCallback: "otmjsonp",
    async: false,
    success: function(data) {
      resultData = origData = data;

      // make the UI visible
      setupHTML(JSON);
    }
    });

});

You access an Object property like: Object.property or Object['some property'] . You can use a for in loop to loop over Objects, and most Arrays, like:

var property, value;
for(var i in Object){
  property = i;
  value = Object[i];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM