简体   繁体   English

从js中的嵌套object中提取键值

[英]Extract key value from a nested object in js

How should I extract key from a nested object If i enter Mumbai, I want to get Maharashtra and India.If The user will enter value like 'Dallas', then it should return Texas and USA我应该如何从嵌套的 object 中提取密钥如果我进入孟买,我想获得马哈拉施特拉邦和印度。如果用户输入像“达拉斯”这样的值,那么它应该返回德克萨斯和美国

obj = {
       "India":
          {
            "Karnataka": ["Bangalore", "Mysore"],
            "Maharashtra": ["Mumbai", "Pune"]
          },
      "USA": 
          {
           "Texas": ["Dallas", "Houston"],
           "IL": ["Chicago", "Aurora", "Pune"]
          }
      }

Edit: After rereading the question and comments from @iAmOren.编辑:重读@iAmOren 的问题和评论后。

Let's recurse through the tree.让我们通过树递归。 This will work for any tree depth.这适用于任何树深度。 It will also find a State or a Country (or in other words, any key or value at any level).它还将找到 State 或国家/地区(或者换句话说,任何级别的任何键或值)。

Edit 2: Thanks for the feedback again, @iAmOren.编辑 2:再次感谢您的反馈,@iAmOren。 Now, it finds all instead of "find first" in my last solution.现在,它在我的最后一个解决方案中找到了所有而不是“查找第一个”。

 var obj = { "India": { "Karnataka": ["Bangalore", "Mysore", "Texas"], "Maharashtra": ["Mumbai", "Pune"] }, "USA": { "Texas": ["Dallas", "Houston"], "IL": ["Chicago", "Aurora", "Pune"] } }; var getParents = function(o, toFind, found, path) { if (path === undefined) path = []; for(var key in o) { // Matches city or the parent nodes (country or state). if (o[key] === toFind || key === toFind) { var aFoundPath = Object.assign([], path); aFoundPath.push(toFind); found.push(aFoundPath); } else { if (typeof o[key] == "object") { path.push(key); getParents(o[key], toFind, found, path); path.pop(); } } } }; var printParents = function(toFind) { var outFound = []; getParents(obj, toFind, outFound); console.log(outFound); }; printParents("Mumbai"); printParents("Pune"); printParents("Texas");

Here's my answer from a (very) similar question.这是我对(非常)类似问题的回答。 It returns an array of array of country and state.它返回一个国家数组和 state 数组。

function findCity(city) {
  var result=[];
  for(country in obj) {
    for(state in obj[country]) {
      if(obj[country][state].includes(city)) {
        result.push([country, state]);
      }
    }
  }
  return result;
}

Note to possible down-voters:注意可能的投票者:
Please explain why in detail instead.请详细解释原因。
Don't be a troll.不要成为巨魔。
Thank you!谢谢!

You can loop through the object and find the respective keys by matching the value:您可以遍历 object 并通过匹配值找到相应的键:

 var obj = { "India": { "Karnataka": ["Bangalore", "Mysore"], "Maharashtra": ["Mumbai", "Pune"] }, "USA": { "Texas": ["Dallas", "Houston"], "IL": ["Chicago", "Aurora", "Pune"] } } var country, state; var city = 'Mumbai'; for(var k in obj){ for(var j in obj[k]){ if(obj[k][j].includes(city)){ country = k; state = j; } } } console.log(country + ', ' + state);

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

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