javascript – JS将数组转换为json链表?

前端之家收集整理的这篇文章主要介绍了javascript – JS将数组转换为json链表?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我是JS的新手,组织数据的概念让我觉得有点困难,试图从特定的数组格式中获取数据(因为这是我必须使用的)并将其输出为另一种特定的JSON格式.

这是为了将数据传递给D3 sankey模块
https://github.com/d3/d3-plugins/blob/master/sankey/sankey.js

我无法弄清楚如何将节点的索引添加链接中,而不是名称.

真的,我完全迷失了!
我在这里做了一个小提琴:
https://jsfiddle.net/adamdavi3s/kw3jtzx4/

以下是所需数​​据和输出的示例

var data= [
    {"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},"target":"Losses","value":"26.862"},"target":"Liquid","value":"280.322"},{"source":"Losses","value":"280.322"}
];


 var output= { 
     "nodes":[
         {"name":"Agricultural 'waste'"},{"name":"Bio-conversion"},{"name":"Electricity grid"},{"name":"Losses"},{"name":"Liquid"}
     ],"links":[
         {"source":0,"target":1,"value":124.729},{"source":1,"target":2,"value":0.597},"target":3,"value":26.862},"target":4,"value":280.322},{"source":3,"value":280.322}
     ]
 };

这是我的代码来自小提琴

var data=[{"source":"Agricultural 'waste'","value":"280.322"}
];

var sourceArray=[];

for (var i=0; i 
最佳答案
Array.reduce()非常适合这个用例;)

看一看.

var data=[{"source":"Agricultural 'waste'","value":"280.322"}
];


var output = data.reduce(function(result,item){
  for(key in search = ['source','target']) {
    var value = item[search[key]];
    
    if(! result.index.hasOwnProperty(value)){
       result.index[value] = Object.keys(result.index).length;
       result.nodes.push({name: value});
    }
  }
  
  result.links.push({
    source: result.index[item.source],target: result.index[item.target],value: Number(item.value)
  });
  
  return result;
},{nodes: [],links: [],index: {}});

delete output.index;
console.log(output);
原文链接:https://www.f2er.com/jquery/428441.html

猜你在找的jQuery相关文章