如何构建用于动态查找值的 JSON 键

背景


我正在创建一个引擎来从different JSON文件中获取值,每个文件都带有different structure. 我正在寻找进入store the key as string (or array)静态文件的方法,并使用键来获取值。


要存储在静态文件中的字符串或数组形式的键可能看起来像hello.world.that.is.somethingandthat.is.something.different或在数组["hello", "world", "that", "is", "something"]and中["that", "is", "something", "different"]。


鉴于下面的示例数据,有什么方法可以从预构建密钥(存储在某处)中检索值[1, 2, 3, 4, 5]和值?Noo!!!


样本数据


let data = {

  hello: {

    world: {

      that: {

        is: {

          something: [1, 2, 3, 4, 5]

        }

      }

    }

  },

  that: {

    is: {

      something: {

        different: "Noo!!!"

      }

    }

  }

}

预期数据


data[pre_build_keys_1] // [1, 2, 3, 4, 5]

data[pre_build_keys_2] // Noo!!!


青春有我
浏览 147回答 4
4回答

GCT1015

您可以使用eval()它评估字符串并将其视为节点/变量,假设您已经声明了一个与评估的字符串等效的变量名称。let data = {  hello: {    world: {      that: {        is: {          something: [1, 2, 3, 4, 5]        }      }    }  },  that: {    is: {      something: {        different: "Noo!!!"      }    }  }}let pre_build_keys_1 = "data.hello.world.that.is.something"let pre_build_keys_2 = "data.that.is.something.different"console.log(eval(pre_build_keys_1))console.log(eval(pre_build_keys_2))

梵蒂冈之花

假设数据结构稳定且与示例一致,我认为您已经完成了所有艰苦的工作!在这一点上,您可以评估您想要的确切路径并返回它。console.log(eval("data.hello.world.that.is.something"));console.log(eval("data.that.is.something.different"));

RISEBY

您可以像下面这样创建函数并使用数组getData传递data对象。单击此处了解更多关于used in 的信息。keyreducegetDatafunction getData(data, keys) {  return keys.reduce((acc, key) => acc[key], data);}let pre_build_keys_1 = ["hello", "world", "that", "is", "something"];let pre_build_keys_2 = ["that", "is", "something", "different"]let data = {  hello: {    world: {      that: {        is: {          something: [1, 2, 3, 4, 5]        }      }    }  },  that: {    is: {      something: {        different: "Noo!!!"      }    }  }};console.log(getData(data, pre_build_keys_1)); // [1, 2, 3, 4, 5]console.log(getData(data, pre_build_keys_2)); // Noo!!!

开心每一天1111

你可以创建一个代理对象来处理从对象中获取适当的项目,然后你可以从字面上做data['hello.world.that.is.something']来获取你想要的东西,就像这样:let real_data = {  hello: {    world: {      that: {        is: {          something: [1, 2, 3, 4, 5]        }      }    }  },  that: {    is: {      something: {        different: "Noo!!!"      }    }  }}const handler = {  get: function(target, prop, receiver) {    let parsed;    try {        parsed = JSON.parse(prop);    } catch (e) {      if (prop.startsWith('[')) {          parsed = prop.substring(1, prop.length - 1);          parsed = parsed.split(', ').join(',').split(',');      } else {          parsed = prop.split('.');      }    }    return parsed.reduce((carry, current) => carry[current], target);  }};const data = new Proxy(real_data, handler);console.log(data['hello.world.that.is.something'])console.log(data['[that, is, something, different]'])console.log(data['["that", "is", "something", "different"]'])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript