将JSON对象的键转换为点表示法路径 [英] Convert a JSON object's keys into dot notation paths

查看:153
本文介绍了将JSON对象的键转换为点表示法路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有使用已知点符号访问深层对象,而是想要反过来:从深层对象的键构建点符号字符串。

Instead of accessing a deep object with a known dot notation, I want to do the opposite: build the dot notation string from the keys of the deep object.

因此给出以下JSON对象:

So given the following JSON object:

{
  great:{
    grand:{
      parent:{
        child:1
      },
      parent2:1
    }
  }
}

我想获得以下路径数组:

I'd like to get the following array of paths:

[
  "great.grand.parent.child",
  "great.grand.parent2"
]

提前致谢!

推荐答案

试试这个。但我不知道你为什么需要这个。

Try this. But I don't know why you need this.

function path(a) {
  var list = [];
  (function(o, r) {
    r = r || '';
    if (typeof o != 'object') {
      return true;
    }
    for (var c in o) {
      if (arguments.callee(o[c], r + "." + c)) {
        list.push(r.substring(1) + "." + c);
      }
    }
    return false;
  })(a);
  return list;
}
var a = {
  great:{
    grand:{
      parent:{
        child:1
      },
      parent2:1
    }
  }
};
console.log(JSON.stringify(path(a)));

这篇关于将JSON对象的键转换为点表示法路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆