D3 - 如何根据行索引合并2个数组

时间:2016-12-16 16:47:03

标签: javascript d3.js collections

我正在使用D3进行可视化,需要根据行索引合并2个数组:

var links = 
[
{"source":"a0","target":"a0","s_portfolio":"a","t_portfolio":"a","SOURCE_TYPE":"APP","DES_TYPE":"APP"},
{"source":"a1","target":"a2","s_portfolio":"a","t_portfolio":"c","SOURCE_TYPE":"APP","DES_TYPE":"APP"},
{"source":"a1","target":"a2","s_portfolio":"a","t_portfolio":"c","SOURCE_TYPE":"APP","DES_TYPE":"APP"}  
];

var files =
[
{"File_Desc":"","DataName":""},
{"File_Desc":"Date","DataName":"Dates.01012016"},
{"File_Desc":"Address","DataName":"Address.01012016"}    
    ];

获得:

var result =
[
{"source":"a0","target":"a0","s_portfolio":"a","t_portfolio":"a","SOURCE_TYPE":"APP","DES_TYPE":"APP","File_Desc":"","DataName":""},
{"source":"a1","target":"a2","s_portfolio":"a","t_portfolio":"c","SOURCE_TYPE":"APP","DES_TYPE":"APP","File_Desc":"Date","DataName":"Dates.01012016"},
{"source":"a1","target":"a2","s_portfolio":"a","t_portfolio":"c","SOURCE_TYPE":"APP","DES_TYPE":"APP","File_Desc":"Address","DataName":"Address.01012016"}
]

4 个答案:

答案 0 :(得分:3)

试试这个:

var links = [
  {"source":"a0","target":"a0","s_portfolio":"a","t_portfolio":"a","SOURCE_TYPE":"APP","DES_TYPE":"APP"},
  {"source":"a1","target":"a2","s_portfolio":"a","t_portfolio":"c","SOURCE_TYPE":"APP","DES_TYPE":"APP"},
  {"source":"a1","target":"a2","s_portfolio":"a","t_portfolio":"c","SOURCE_TYPE":"APP","DES_TYPE":"APP"}  
];

var files = [
  {"File_Desc":"","DataName":""},
  {"File_Desc":"Date","DataName":"Dates.01012016"},
  {"File_Desc":"Address","DataName":"Address.01012016"}    
];

var result = [];

for(let i = 0; i < links.length; i++){
  result[i] = Object.assign(links[i], files[i]);
}

console.log(result);

答案 1 :(得分:3)

如果你可以使用最新型号的JavaScript(又名ES2015), 最短的路径就像:

var result = links.map((d,i) => Object.assign({}, d, files[i]));

这很简短。它也不会修改linksfiles(如果您希望将它们与result分开使用)。

<强> P.S。

评论建议您关注替代解决方案的运行时间。一般来说,他们都可以,尤其是。作为d3应用程序中常见的一次性数据设置。但是,如果您有大型数据集或经常运行记录合并,那么您可能需要优化。

如果您愿意更新现有记录集而不是创建新记录集:

links.forEach((d,i) => Object.assign(d, files[i]));

在此之后,links具有更新的记录。这比其他解决方案快7-10倍,可能是因为它没有创建大量新对象。如果您使用原始的,未合并的linksfiles个对象,那么没有特别的理由可以避免这种类型的“破坏性”&#34;或&#34;到位&#34;更新。通常很少需要优化一次性设置操作。但如果你想要或者需要这样做,这是一个很好的方法。

答案 2 :(得分:2)

我可能会使用array map迭代一个数组,然后在我的回调函数中使用this answer中定义的函数返回一个组合对象。

var result = links.map(combineLinkToFile);

function combineLinkToFile (link, index) {

    var file = files[index];

    return collect(link, file)
}

function collect() {
  var ret = {};
  var len = arguments.length;
  for (var i=0; i<len; i++) {
    for (p in arguments[i]) {
      if (arguments[i].hasOwnProperty(p)) {
        ret[p] = arguments[i][p];
      }
    }
  }
  return ret;
}

答案 3 :(得分:0)

使用jQuery map()和extend()方法:

function mergeObjectsInArrays(arr1, arr2){
    return $.map(arr1, function(el, i){
        return $.extend(el, arr2[i]);
    });
};

// then pass your arrays:
var result = mergeObjectsInArrays(links, files);