简体   繁体   English

在javascript对象中查找属性

[英]Finding properties in a javascript object

I have a javascript object, which I have received from a JSONP file. 我有一个javascript对象,我从JSONP文件收到。

The object contains multiple "options" and "results", which are used to adjust the html on the page when a user clicks. 该对象包含多个“选项”和“结果”,用于在用户单击时调整页面上的html。

Right now, I am able to check if the HTML string (inserted via json reference) exists in the json file. 现在,我能够检查json文件中是否存在HTML字符串(通过json引用插入)。 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... 我想要做的是获取该字符串,在json文件中找到下一个“结果”或“选项”,然后返回“选项”或“结果”值,以便我可以使用它来更改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". 我一直在尝试.indexOf方法来查找当前索引,但这并没有真正帮助我找到像“选项”这样的特定属性。

This is the code I'm using to iterate through the JSONP file and find if the current string exists. 这是我用来迭代JSONP文件并查找当前字符串是否存在的代码。

$.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: 这是一个非常简单的大型JSONP文件版本:

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. 如果重新构造JSON以将选项/结果嵌套在相应的父级中,则可以轻松获得所有可能的选项。 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. 我建议在进一步推进之前仔细考虑并组织你的JSON结构。 Organized and logical JSON will make the Javascript easier. 有组织的逻辑JSON将使Javascript更容易。 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: 对于这种情况 - 尽管我可以从描述和示例中收集到 - 我认为JSON结构具有逻辑意义并且在以后的Javascript中证明有用可能看起来像这样:

{
  '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. 这里的部分问题是您如何将UI与数据初始化相结合。 What I think you really want to do is to separate out the JSON request getting the data from the handling of the click. 我认为你真正想做的是分离出JSON请求,从处理点击中获取数据。

$(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'] . 您可以访问Object属性,如: Object.propertyObject['some property'] You can use a for in loop to loop over Objects, and most Arrays, like: 您可以使用for in循环遍历Objects和大多数Arrays,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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