如何在 JavaScript 对象中计算父级(获取未定义错误)

how to counts parent in an javascript object (getting not defined error)

本文关键字:获取 未定义 错误 计算 JavaScript 对象      更新时间:2023-09-26

我正在尝试制作一个对象,该对象可以包含元素的父级数量。我有一个对象数组,其中有两个字段来往我想计算父母的长度这是我的代码?

  • "node_from":11、没有父母..它不必字段,所以它的长度是0,0;
  • "node_from":12,来自 11 .所以它有父级,所以它的父长度是 1 或 1,与 13、14、16、18、19 相同。
  • "node_from":15,有2个父母来自13岁和14岁。所以它的长度是 2 .

我们能找到这个吗

这是我的代码

https://jsfiddle.net/ood2ezvz/2/

var obj={}
for(var i=0;i<node.length;i++){
console.log(node[i]);
var node=node[i]
if(obj.hasOwnProperty(node.node_from)){
obj[node_from]=obj[node_from]++;
}else{
obj[node_from]=0;
}
}
console.log(obj)

它给出了错误?

预期输出{ 11:0, 12:1, 13:1, 14:1, 15:2, 16:1, 17:1, 18:1 19:1 }

此提案为父项使用一个临时对象,然后返回每个父项的长度。

function getParentCount(nodes) {
    var parent = {}, o = {};
    nodes.forEach(function (n) {
        parent[n.node_from] = parent[n.node_from] || [];
        n.children.forEach(function (a) {
            parent[a.node_to] = parent[a.node_to] || [];
            parent[a.node_to].push(n.node_from);
        });
    });
    Object.keys(parent).forEach(function (k) { o[k] = parent[k].length; });
    return o;
}
var nodes = [{ "node_from": 11, "children": [{ "node_to": 12 }] }, { "node_from": 12, "children": [{ "node_to": 13 }, { "node_to": 14 }] }, { "node_from": 13, "children": [{ "node_to": 15 }] }, { "node_from": 14, "children": [{ "node_to": 15 }] }, { "node_from": 15, "children": [{ "node_to": 16 }, { "node_to": 17 }, { "node_to": 18 }] }, { "node_from": 16, "children": [] }, { "node_from": 17, "children": [] }, { "node_from": 18, "children": [{ "node_to": 19 }] }, { "node_from": 19, "children": [] }];
document.write('<pre>' + JSON.stringify(getParentCount(nodes), 0, 4) + '</pre>');

我已经用这个jsfiddle修复了你的代码。

https://jsfiddle.net/ood2ezvz/8/

从本质上讲,您在这种情况下错误地使用了hasOwnProperty。 看起来运作良好的是undefined . 下面的代码获取您要查找的确切输出。 计算子项中有多少个node_to,并将原始node_from设置为 0。

var obj = {};
for (var i = 0; i < node.length; i++) {
    var new_node = node[i];
  console.log(new_node);
  if (typeof obj[new_node.node_from] === 'undefined') {
    obj[new_node.node_from] = 0;
  }
  for (var j = 0; j < new_node.children.length; j++) {
    if (typeof obj[new_node.children[j].node_to] !== 'undefined') {
        obj[new_node.children[j].node_to]++;
    }
  }
}
console.log(obj);

假设"node_from"是当前节点的ID,"node_to"是每个节点指向的子节点。这是一个可以计算每个节点的子节点的函数。

var node=[
  {
   
    "node_from": 11,
    "children": [
      {
        "node_to": 12
      }
    ]
  },
  {
   
    "node_from": 12,
    "children": [
      {
        "node_to": 13
      },
      {
        "node_to": 14
      }
    ]
  },
  {
    "node_from": 13,
    "children": [
      {
        "node_to": 15
      }
    ]
  },
  {
    
    "node_from": 14,
    "children": [
      {
        "node_to": 15
      }
    ]
  },
  {
   
    "node_from": 15,
    "children": [
      {
        "node_to": 16
      },
      {
        "node_to": 17
      },
      {
        "node_to": 18
      }
    ]
  },
  {
    
    "node_from": 16,
    "children": [
      
    ]
  },
  {
    "node_from": 17,
    "children": [
      
    ]
  },
  {
    
    "node_from": 18,
    "children": [
      {
        "node_to": 19
      }
    ]
  },
  {
    
    "node_from": 19,
    "children": [
      
    ]
  }
];
function countParents(nodes, num){
  var count = 0;
  for(var i=0;i<nodes.length;i++){
  	if(nodes[i].children){
    	for(var e=0;e<nodes[i].children.length;e++){
        if(nodes[i].children[e].node_to == num)
          count++;
      }
    }
  }
  return count;
}
function countEachParents(nodes){
  var output = [];
  for(var i=0;i<nodes.length;i++){
    output.push( nodes[i].node_from + ":" + countParents(nodes, nodes[i].node_from) );
  }
  return output;
}
document.getElementById( "output" ).innerHTML = countEachParents(node).join(", ");
{<span id='output'></span>}

https://jsfiddle.net/zwttLty7/

就个人而言,我会使用 OOP 和方法来处理这样的事情......

function Node(id, children){
  this.id = id;
  this.children = children || [];
  this.countParents = function(nodeList){
    var count = 0;
    for(var i=0;i<nodeList.length;i++){
      if(nodeList.children.indexOf(this.id) > -1)
        count++;
    }
    return count;
  };
};
function NodeList(nodes){
  this.list = nodes || [];
  this.parentCounts = function(){
    var output = [];
    for(var i=0;i<this.list.length;i++){
      var count = 0;
      for(var e=0;e<this.list.length;e++){
        if(this.list[e].children.indexOf(this.list[i].id) > -1)
          count++;
      }
      output.push(this.list[i].id+":"+count);
    }
    return output.join(", ");
  }
};
var nodes = new NodeList([
  new Node(11, [12]),
  new Node(12, [13,14]),
  new Node(13, [15]),
  new Node(14, [15]),
  new Node(15, [16,17,18]),
  new Node(16),
  new Node(17),
  new Node(18, [19]),
  new Node(19)
]);
document.getElementById("output").innerHTML = nodes.parentCounts();
{<span id='output'></span>}

https://jsfiddle.net/otcm76oy/

你需要创建一个递归函数,如下所示:

var node = [{
  "node_from": 11,
  "children": [{
    "node_to": 12
  }]
}, {
  "node_from": 12,
  "children": [{
    "node_to": 13
  }, {
    "node_to": 14
  }]
}, {
  "node_from": 13,
  "children": [{
    "node_to": 15
  }]
}, {
  "node_from": 14,
  "children": [{
    "node_to": 15
  }]
}, {
  "node_from": 15,
  "children": [{
    "node_to": 16
  }, {
    "node_to": 17
  }, {
    "node_to": 18
  }]
}, {
  "node_from": 16,
  "children": [
  ]
}, {
  "node_from": 17,
  "children": [
  ]
}, {
  "node_from": 18,
  "children": [{
    "node_to": 19
  }]
}, {
  "node_from": 19,
  "children": [
  ]
}]
function recursiveSearch(node_from, count) {
  for (var i = 0; i < node.length; i++) {
    var current = node[i];
    for (var j = 0; j < current.children.length; j++) {
      var child = current.children[j];
      if (node_from == child.node_to)
        recursiveSearch(current.node_from, ++count);
    }
  }
  return count;
}
var obj = {}
for (var i = 0; i < node.length; i++) {
  var current = node[i]
  if (current.hasOwnProperty('node_from')) {
    obj[current.node_from] = recursiveSearch(current.node_from, 0);
  }
}
document.write('<pre>' + JSON.stringify(obj) + '</pre>')
console.log(obj)

试试这个方法

var obj={}
node.forEach(function(object){
    if(!obj[object.node_from])
      obj[object.node_from] = 0;
    object.children.forEach(function(child){
        if(!obj[child.node_to])
          obj[child.node_to] = 0;
        obj[child.node_to]++;
    })
})
console.log(obj);