【问题标题】:find the json path for a specific value using javascript使用 javascript 查找特定值的 json 路径
【发布时间】:2021-11-19 20:38:49
【问题描述】:

如何使用 javascript 查找特定值的 json 路径

var data = {
    key1: {
        children: {
            key2:'value',
            key3:'value',
            key4: value
        }, 
    key5: 'value'
}

上述data.key1.children.key3的预期结果

任何帮助将不胜感激。

【问题讨论】:

  • 有了JSON.parse() 和myVal['key'],你可以去任何地方

标签: javascript json angular typescript


【解决方案1】:

此函数返回您的(任何)对象中的所有可用路径: 使用此功能,您可以获得 ["key1.children.key2", "key1.children.key3", "key1.children.key4", "key1.key5"]

function allPaths(root) {
  let stack = [];
  let result = [];

  // checks if object
  const isObject = value => typeof value === "object";

  stack.push(root);
  while (stack.length > 0) {
    let node = stack.pop();
    if (isObject(node)) {
      Object.entries(node).forEach(([childNodeKey, childNodeValue]) => {
        if (isObject(childNodeValue)) {
          const newObject = Object.fromEntries(
            Object.entries(childNodeValue).map(([cnk, cnv]) => {
              return [`${childNodeKey}.${cnk}`, cnv];
            })
          );
          stack.push(newObject);
        } else {
          stack.push(`${childNodeKey}`);
        }
      })
    } else {
      result.push(node);
    }
  }
  return result.reverse();
}

如果对你有帮助,请在 cmets 中告诉我

【讨论】:

    【解决方案2】:

    var str = "key3"; 数据["key1"]["children"][str];

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-14
      • 2020-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-13
      相关资源
      最近更新 更多