Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/376.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用JSON.stringify将JavaScript对象转换为树_Javascript_Json - Fatal编程技术网

使用JSON.stringify将JavaScript对象转换为树

使用JSON.stringify将JavaScript对象转换为树,javascript,json,Javascript,Json,我最近一直在使用以树的形式显示嵌套的JSON对象,就像LinuxCLI工具的输出tree 只有JSON.stringify才能得到相同的结果吗?我知道JSON.stringify接受3个参数:value、replace和space() 我问了这个问题,因为我发现空格可以是一个字符串,而不仅仅是一个数字 该解决方案应尽可能通用,但如果需要任何示例,请参考以下示例: 是否可以从replacer函数访问space参数作为起点?将常量值作为间隔符,并且不会对嵌套项进行更改,这是必需的,因为您有两个不同的

我最近一直在使用以树的形式显示嵌套的JSON对象,就像LinuxCLI工具的输出
tree

只有
JSON.stringify
才能得到相同的结果吗?我知道JSON.stringify接受3个参数:value、replace和space()

我问了这个问题,因为我发现空格可以是一个字符串,而不仅仅是一个数字

该解决方案应尽可能通用,但如果需要任何示例,请参考以下示例:

是否可以从
replacer
函数访问
space
参数作为起点?

将常量值作为间隔符,并且不会对嵌套项进行更改,这是必需的,因为您有两个不同的项字符串和两个作为嵌套项前缀的字符串

相反,您可以采用递归方法,通过为每一行传递前缀来获取自定义函数

函数getFormatted(对象,前缀){ var结果=“”; Object.entries(Object.forEach)([k,v],i,{length})=>{ 结果+=前缀+(i+1==长度?)└─ ' : '├─ ') + K if(v&&typeof v=='object'){ 结果+='\n'; 结果+=getFormatted(v,前缀+(i+1==长度?“”:'│ ')); }否则{ 如果(v)结果+=':'+v; 结果+='\n'; } }); 返回结果; } const x={橙子:{普通话:{clementine:null,橘子:{又便宜又多汁!'},苹果:{gala:null,'pink lady':null},其他:['pananas','ananas','pear']}; console.log(getFormatted(x.))
。作为控制台包装器{max height:100%!important;top:0;}
请添加一个数据示例和所需结果。使用stringify和spacer更改字符串是不可能的。感谢您花时间讨论一个如此快速的被否决问题。很好的递归函数!为什么它被否决了,因为我已经学到了一些东西。。。
JSON.strinfify(value, replacer, space)
const x = {
  oranges: { mandarin: { clementine: null, tangerine: 'so cheap and juicy!' } },
  apples: { gala: null, 'pink lady': null },
  others: [ 'bananas', 'ananas', 'pear' ]
}
->
> console.log( treeify.asTree(x, true, true) )
├─ oranges
│  └─ mandarin
│     ├─ clementine
│     └─ tangerine: so cheap and juicy!
├─ apples
│  ├─ gala
│  └─ pink lady
└─ others
   ├─ 0: bananas
   ├─ 1: ananas
   └─ 2: pear