迭代动态创建的嵌套数组

时间:2017-04-11 12:42:58

标签: javascript arrays

我有一个对象数组,每个对象可以包含更多对象数组,依此类推。我想迭代所有这些对象而不用硬编码。我不知道每个对象有多少嵌套数组。

// This is the parent array
var members = [Object, Object, Object, Object, Object];

// members[0] can have another array of objects
var member = members[0];

and so on....
var mem = member[0];

我想迭代所有这些对象,但就像我说的,我不知道会有多少。我需要获得Object.label目前获得的每个对象的标签 我希望我解释得很好,这是图片。 在我的例子中,Array [5]是var成员 enter image description here

5 个答案:

答案 0 :(得分:2)

我会用遍历所有子节点的递归函数来解决这个问题。鉴于它们都具有相同的结构。

function visit(o) {
  for (var i = 0; i<o.length; i++) {        
    /* do something useful */
    console.log(o[i].label);

    if (Array.isArray(o[i].children)) {
      visit(o[i].children);
    }
  }
}

答案 1 :(得分:0)

试试这个。使用Js Array.isArray 检查子元素是否为数组,如果是数组,则再次调用函数 someFn

function someFn(members) {
var labels=[]
for (var i = 0; i<members.length; i++) { 
    labels.push(members[i].label)

    if (Array.isArray(members[i]) && members[i].length>0) {
      someFn(members[i]);
    }
  }
retun labels;
}
var membersArray = [Object, Object, Object, Object, Object];
var labelsArray= someFn(membersArray);
console.log(labelsArray);

我稍后会添加一些演示

答案 2 :(得分:0)

您可以编写一个函数,给定object它将读取此对象中的label属性,并循环遍历此对象的children数组(如果存在)。

function readObj(obj){
  console.log(obj.label);
  if(obj.children && obj.children.length>0){
       obj.children.map(readObj);
  }
}

然后将此函数应用于所有members数组。

&#13;
&#13;
function readObj(obj) {
  console.log(obj.label);
  if (obj.children && obj.children.length > 0) {
    obj.children.map(readObj);
  }
}

var members = [{
  label: "label1"
}, {
  label: "Label2",
  children: [{
    label: "child1"
  }, {
    label: "child2"
  }]
}, {
  label: "label3",
  children: [{
    label: "child3"
  }]
}];

members.map(readObj);
&#13;
&#13;
&#13;

答案 3 :(得分:0)

另一种方式:

function getMembers(list){
  list.forEach(function(item){
    console.log(item.label); 
    if(item.children){
      getMembers(item.children)
    }
  });
}

var members = [{label: 'label1', children:[{label: 'label21'}, {label: 'label22'}]}, {label: 'label2'}, {label: 'label3'}];

getMembers(members);

答案 4 :(得分:0)

    var jsonArr = [{"children":["New1","New2","New3","New4"]},{"children1":
                  ["New11","New12","New13","New14"],"children2":
                  ["New21","New22","New23","New24"]},{"children2":
                  ["New21","New22","New23","New24"]}];

	function callRecFunc(obj){
		$.each(obj,function(i,o){
			if(o != undefined && o instanceof Array){
				callRecFunc(o);
			}
			else{
				console.log(o);
			}
		});
	}

	$.each(jsonArr,function(ind,obj){
			callRecFunc(obj);
	})
   
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>