评估多维对象中的键值

时间:2016-11-17 21:19:39

标签: javascript d3.js

我有一个看起来像这样的多维对象:

{
 "links": [{"source":"58","target":"john","total":"95"},
           {"source":"60","target":"mark","total":"80"}],
 "nodes": 
          [{"name":"john"}, {"name":"mark"}, {"name":"rose"}]
}

我正在尝试评估“链接”中“总计”的价值。我可以在一维数组中执行此操作,如下所示:

for (var i = 0; i < data.length; i++) {
    for (var key in data[i]) {
        if (!isNaN(data[i][key])) {
            data[i][key] = +data[i][key];
        }
    }
};

但是我无法弄清楚如何在二维中做到这一点(特别是按名称调用键“total”的值)。

有人能让我走上正轨吗?谢谢!

3 个答案:

答案 0 :(得分:2)

从数组结构的原理开始,您可以迭代键和值:

&#13;
&#13;
var obj = {
 "links": [{"source":"58","target":"john","total":"95"},
           {"source":"60","target":"mark","total":"80"}],
 "nodes": 
          [{"name":"john"}, {"name":"mark"}, {"name":"rose"}]
};

for (var key in obj){
  obj[key].forEach(function(item){
    for(var subkey in item){
      if (subkey == 'total')
        console.log(item[subkey]);
    };
  });
};
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用reduce

获得总计

检查此代码段

&#13;
&#13;
var obj = {
  "links": [{
    "source": "58",
    "target": "john",
    "total": "95"
  }, {
    "source": "60",
    "target": "mark",
    "total": "80"
  }, {
    "source": "60",
    "target": "mark",
    "total": "80"
  }],
  "nodes": [{
    "name": "john"
  }, {
    "name": "mark"
  }, {
    "name": "rose"
  }]
}

var links = obj.links;
var sum = links.map(el => el.total).reduce(function(prev, curr) {
  return parseInt(prev, 10) + parseInt(curr, 10);

});
console.log(sum);
&#13;
&#13;
&#13;

希望有所帮助

答案 2 :(得分:0)

从数组中提取值,将它们转换为数字并添加它们。

Array.prototype.map()Array.prototype.reduce()非常有用:

var data = {"links":[{"source":"58","target":"john","total":"95"},{"source":"60","target":"mark","total":"80"}], "nodes":[{"name":"john"}, {"name":"mark"}, {"name":"rose"}]};

var sum = data.links.map(function(link) {
  return +link.total;
}).reduce(function(a, b) {
  return a + b;
});

console.log(sum);