我设法解决了这个问题,但将字符串重建为可以轻松推入数组的格式
这是代码
var str='[{"id":170},{"id":171,"children":[{"id":172},{"id":173}]},{"id":174,"children":[{"id":176},{"id":177}]},{"id":175}]';
for(var d=0; d<str.length;d++){
if(newstr!=''){str=newstr;}
var childrenstart=str.indexOf("children");
if(childrenstart!="-1"){
var endstr=str.substr(childrenstart).indexOf("]");;
var childrenstring=str.substr(childrenstart,endstr);
var cleanchildrenstr=childrenstring.replace(/children":/gi,'');
var newchildrenstrng=cleanchildrenstr.replace(/id/gi,'child');
newstr=str.substr(0,childrenstart-1)+newchildrenstrng+str.substr(childrenstart+endstr);
d=childrenstart+endstr;
} else {
d=str.length;
}
}
var finalstr=str.replace(/{/gi,'');
var finalstr=finalstr.replace(/}/gi,'');
var finalstr=finalstr.replace(/]/gi,'');
var finalstr=finalstr.replace(/\[/gi,'');
var finalstr=finalstr.replace(/\"/gi,'');
我知道这可以写得更聪明、更整洁,但它是初稿并且有效。这将返回一个字符串
id:170,id:171,child:172,child:173,id:174,id:175
可以切碎并推入阵列