猿问

递归方法转换,直到数组耗尽

我的代码中有一个笨拙且无法缩放的方法。


y是一个具有键/值类对象的数组对象,具有两个属性:


name唯一的字符串属性:该值由children属性区分,它是另一个与 y 对象类型相同的数组。


for (var i = 0; i < y.length; i++) {

  let objx = y[i];

  let name = objx["name"];

  let inner = objx["children"];


  for (var i = 0; i < inner.length; i++) {

    var z = inner[i]["name"];

    let h = inner[i]["children"];

    console.log(h);

  }


  // more for loops on the h object now, and so on.

}

是否有可能有一个方法来构建一个包含所有名称字符串属性的新集合,直到所有相应的子属性返回 0 计数?


狐的传说
浏览 141回答 3
3回答

潇湘沐

let y = {&nbsp; name: 'parent',&nbsp; children: [&nbsp; &nbsp; {name: 'child1', children: []},&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; name: 'child2', children: [&nbsp; &nbsp; &nbsp; &nbsp; {name: 'grandChild1', children: []}&nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; },&nbsp; ]};let getNames = y => [y.name, ...y.children.flatMap(getNames)];let names = getNames(y);console.log(names);

倚天杖

您可以采用递归函数。const&nbsp; &nbsp; getNames = array => array.flatMap(({ name, children }) => [name, ...getNames(children)]);&nbsp; &nbsp;&nbsp;var array = [{ name: 'parent', children: [{ name: 'child1', children: [] }, { name: 'child2', children: [{ name: 'grandChild1', children: [] }] }] }];console.log(getNames(array));

守候你守候我

这是基本递归。制作一个循环数据并与孩子一起调用自身的函数。var myData = [{&nbsp; name: 'foo',&nbsp; children: [{&nbsp; &nbsp; name: 'foo-1',&nbsp; &nbsp; children: [{&nbsp; &nbsp; &nbsp; name: 'foo-1-1'&nbsp; &nbsp; }]&nbsp; }, {&nbsp; &nbsp; name: 'foo-2',&nbsp; &nbsp; children: [{&nbsp; &nbsp; &nbsp; name: 'foo-2-1'&nbsp; &nbsp; }]&nbsp; }]}]function loopOver(array, result) {&nbsp; array.forEach( function (data) {&nbsp; &nbsp; console.log(data.name)&nbsp; &nbsp; result.push(data.name)&nbsp; &nbsp; if (data.children) {&nbsp; &nbsp; &nbsp; return loopOver(data.children, result)&nbsp; &nbsp; }&nbsp; })&nbsp; return result}console.log(loopOver(myData, []))
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答