具有包含其他JSON的数组的单个JSON

问题描述 投票:-1回答:1

我在处理JSON对象时遇到麻烦。我必须创建一个这样的JSN:

{
 name: 'root',
 children: [
     name: 'son1',
     children: [....]
 ]
}

如何使用Javascript构建它?预先感谢。

javascript json hierarchy
1个回答
0
投票

我认为您是指使用对象进行扩展?然后呼叫JSON.stringify()

function MyObject(name) {
  this.name = name,
  this.children = [],
  this.addChild = (child) => {
    this.children.push(child);
  }
}

const root = new MyObject("root");

for(let x=0; x<10; x++) {
  let child = new MyObject(`child ${x}`);
  root.addChild(child);
}

document.querySelector('pre').innerHTML = JSON.stringify(root);
<pre>

</pre>
© www.soinside.com 2019 - 2024. All rights reserved.