如何在包含具有数组值的子对象的对象中搜索值

我有 json 对象,我想在其中搜索一个键,如果键匹配,则返回该对象键作为结果。考虑下面的例子


obj = {

    "India": {

        "Karnataka": ["Bangalore", "Mysore"],

        "Maharashtra": ["Mumbai", "Pune"]

    },

    "USA": {

        "Texas": ["Dallas", "Houston"],

        "IL": ["Chicago", "Aurora", "Pune"]


    }

}

input: Pune

output: ['Maharashtra','IL']


慕田峪9158850
浏览 80回答 4
4回答

胡说叔叔

你可以试试这个-const obj = {  "India" : {    "Karnataka" : ["Bangalore", "Mysore"],    "Maharashtra" : ["Mumbai", "Pune"]  },  "USA" : {    "Texas" : ["Dallas", "Houston"],    "IL" : ["Chicago", "Aurora", "Pune"]  }};const search = (obj, keyword) => {  return Object.values(obj).reduce((acc, curr) => {      Object.entries(curr).forEach(([key, value]) => {        if (value.indexOf(keyword) > -1) {          acc.push(key);        }      });    return acc;  }, []);}console.log(search(obj, 'Pune'));这将搜索keyword数组中是否存在。如果然后将钥匙推入reduce蓄电池。

LEATH

假设您的数据将始终采用 country:state:city 的形式,您可以执行以下操作。获取键的数组,如下所示:keys = Object.keys(obj);然后遍历每个键:function classify(input){res = [];Object.keys(obj).forEach((key)=>{   states = obj[key];   Object.keys(states).forEach((stateKey)=>{      if(states[stateKey].includes(input)){         res.push([stateKey,key]);      }   })})return(res);}这也将返回一个包含国家/地区的数组:input: Puneoutput: [['Maharashtra','India'],['IL','USA']]

万千封印

const input = "Pune"const result = []for (v1 in obj) {&nbsp; for (v2 in obj[v1]) {&nbsp; &nbsp; for (let i = 0; i < obj[v1][v2].length; i++) {&nbsp; &nbsp; &nbsp; if (obj[v1][v2][i] === input) {&nbsp; &nbsp; &nbsp; &nbsp; result.push([v2][0])&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }}

SMILET

function isObject (variable) {&nbsp;return variable !== undefined && variable !== null && variable.constructor === Object}function find(obj,value,keyPath = []){&nbsp; &nbsp;let values = Object.values(obj)&nbsp;&nbsp; &nbsp;let keys = Object.keys(obj)&nbsp;&nbsp;&nbsp; &nbsp;for(let i in values){&nbsp; &nbsp; &nbsp; if(isObject (values[i])) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;find(values[i],value,keyPath )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; }else if(Array.isArray(values[i])){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;let foundValue = values[i].find(e=>value==e)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(foundValue ){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; keyPath.push(keys[i])&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;}&nbsp; &nbsp;return keyPath&nbsp;}obj = { "India": { "Karnataka": ["Bangalore", "Mysore"], "Maharashtra": ["Mumbai", "Pune"] }, "USA": { "Texas": ["Dallas", "Houston"], "IL": ["Chicago", "Aurora", "Pune"] } }console.log(find(obj,"Dallas"))这应该这样做。它应该能够做任何深度。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript