JS converting an array to a json linked list? - javascript

I am new to JS and the concepts of organising data elude me a little, trying to take data from a specific array format (as this is what I have to work with) and output it into another specific JSON format.
This is to pass data to the D3 sankey module
https://github.com/d3/d3-plugins/blob/master/sankey/sankey.js
I can't figure out is how to add the index of the node into the links, rather than the name.
Really I am just totally lost with it!
I made a fiddle here:
https://jsfiddle.net/adamdavi3s/kw3jtzx4/
Below is an example of the data and the output required
var data= [
{"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},
{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},
{"source":"Bio-conversion","target":"Losses","value":"26.862"},
{"source":"Bio-conversion","target":"Liquid","value":"280.322"},
{"source":"Losses","target":"Liquid","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},
{"source":1,"target":3,"value":26.862},
{"source":1,"target":4,"value":280.322},
{"source":3,"target":4,"value":280.322}
]
};
Here is my code from the fiddle thusfar
var data=[{"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},
{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},
{"source":"Bio-conversion","target":"Losses","value":"26.862"},
{"source":"Bio-conversion","target":"Liquid","value":"280.322"},
{"source":"Losses","target":"Liquid","value":"280.322"}
];
var sourceArray=[];
for (var i=0; i <data.length; i++ ) {
var node= {"name":data[i].source};
var found = jQuery.inArray(node, sourceArray);
if (found < 0) {
// Element was not found, add it.
sourceArray.push(node);
}
}
console.log(sourceArray);

In javascript:
[ ] annotations are used to describe an Array, like:
var names=["John","Lisa"]
{ } Its are used to describe an Object
var person = {"name" : "John", "age" : 23}
You can use them inside one another
var people=[{"name" : "John", "age" : 23},{"name" : "Lisa", "age" : 44}]
Try this:
var data=[{"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},
{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},
{"source":"Bio-conversion","target":"Losses","value":"26.862"},
{"source":"Bio-conversion","target":"Liquid","value":"280.322"},
{"source":"Losses","target":"Liquid","value":"280.322"}
];
var sourceArray=[];
var linkArray=[];
for (var i=0; i <data.length; i++ ) {
var node= {"name":data[i].source,};
var link= {
"source":i,
"target":data[i].target,
"value":data[i].value,
};
var found = jQuery.inArray(node, sourceArray);
if (found >= 0) {
// Element was found, remove it.
sourceArray.splice(found, 1);
linkArray.splice(found, 1);
} else {
// Element was not found, add it.
sourceArray.push(node);
linkArray.push(link);
}
}
finalArray={"nodes": sourceArray,"links": linkArray}
console.log(finalArray);
https://jsfiddle.net/9x4rdyy7/

Array.reduce() is perfect for this use case ;)
Take a look.
var data=[{"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},
{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},
{"source":"Bio-conversion","target":"Losses","value":"26.862"},
{"source":"Bio-conversion","target":"Liquid","value":"280.322"},
{"source":"Losses","target":"Liquid","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);

Related

Issue Pushing values in to objects Javascript

Have some issue with push the values in to the javascript array object. Please any one give me the perfect solution
Class code :
var myfuns = ( function(undefined) {
var myarr ={};
function _add(arrayparam){
if (myarr.current == undefined) {
myarr.current = [];
myarr.current.push(options.current_info);
}else{
}
}
function _getList() {
return $.extend(true, {}, myarr);
}
return {
add : _add,
getList : _getList
}
}());
Here am calling and manage the values and keys
function setmydetails(){
var my_param = {
current_info : {
pg : '#tset',
no : 12,
name : "john",
row : 0,
},
userprofile : [],
class : [],
marks : [],
games : []
};
myfuns.add(my_param);
}
Now i got the array
myfuns.getList() // GOT proper array what i passed in my_param
Question : How to modify the existing values from any one of the Inner array from the myarr Obj
Ex: Once First array created later have to modify some from "myarr.current" = > Change current_info.row to 2222
Similar i have to add some array in to " myarr.class " etc
I would like to say try this one not tested
function _add(arrayparam){
if (myarr.current == undefined) {
myarr.current = [];
myarr.current.push(options.current_info);
}else{
$.extend( myarr.current, arrayparam);
}
}
proper source : https://api.jquery.com/jquery.extend/

js each loop add one more depth to an object or array

I have this array of pages urls, now i need to make a hierarchy of out it.
So from this:
allPages = [
{ "url": "/polygon/color/red.html", "name": "Red" },
{ "url": "/polygon/color/blue.html", "name": "Blue" },
{ "url": "/polygon/shape/tri.html", "name": "Triangle" },
{ "url": "/weight/heavy.html", "name": "Heavy Item" }
];
To this:
siteMap = [
polygon:
color:
[{url:"red.html", name:"Red"}],
[{url:"blue.html", name:"Blue"}],
shape:
[{url:"tri.html", name:"Triangle"}],
weight:
[{url:"heavy.html", name:"Heavy Item"}],
];
The final structure can be object or array. But i can only use JS, not jQuery nor php.
EDIT: Changed Input data into array of objects. Sorry for making this harder.
Fiddle: https://jsfiddle.net/ss92kw4a/2/
several steps:
First we split the strings into arrays:
for(i in all){
all[i] = all[i].substring(1).split("/");
}
Next we do a recursive insertion:
function insert(o, a){
if(a.length == 0){return; }
if(!o[a[0]]){
o[a[0]] = {};
}
insert(o[a[0]], a.slice(1));
}
We start the recursion like this:
ans = {};
all.forEach(function(entry){
insert(ans, entry);
});
All done. The result tree is now in the ans object:
console.log(ans);
UPDATE: this code makes the last level an array: https://jsfiddle.net/ss92kw4a/3/
You may use something like this:
var allPages = [
"/polygon/color/red.html",
"/polygon/color/green.html",
"/polygon/color/blue.html",
"/polygon/shape/tri.html",
"/polygon/shape/rect.html",
"/weight/heavy.html",
"/weight/light.html"
];
var siteMap = {};
for (var i in allPages) {
var fragments = allPages[i].match(/[^\/]+/g);
if (!!fragments) {
var currentMember = siteMap;
for (var j in fragments) {
fragment = fragments[j];
if(!currentMember.hasOwnProperty(fragment)) {
currentMember[fragment] = {};
}
currentMember = currentMember[fragment];
}
}
}
Might be enhanced, notably in the fact that ending leaves are objects,
but it works.

Regular expression for accessing map in java script

How to I fetch some rows of particular pattern ?
var list = {
kk_list_name : "jack",
kk_list_no : "123",
kk_first_name :"Reck",
kk_first_no : "5555"
}
Here I want a map with key starting with kk_list
I tried some thing like this, which obviously didnt work.
console.log(list["kk_list_\w+"])
You can try something like this:
function filterArray( list, regex )
{
var outputArray = {};
for( var key in list )
{
if( key.match( regex ) )
{
outputArray[key] = list[key];
}
}
return outputArray;
}
var list = {
kk_list_name : "jack",
kk_list_no : "123",
kk_first_name :"Reck",
kk_first_no : "5555"
}
console.log( filterArray( list, /kk_list_\w+/ ) );
It uses a function to filter the array and make a new one with the regex-selected keys.
You can reduce the object to one with just the keys matching a specified regex using the following:
Object.prototype.reduce = function(regex) {
var newObj = {}, x;
for(x in this) if(this.hasOwnProperty(x) && (!regex || regex.test(x))) newObj[x] = this[x];
return newObj;
};
And then call it as list.reduce(/_first.*$/) => Object {kk_first_name: "Reck", kk_first_no: "5555"}
You can use the following code:
var list = {
kk_list_name : "jack",
kk_list_no : "123",
kk_first_name :"Reck",
kk_first_no : "5555"
}
var line=JSON.stringify(list);
var ar=line.match(/(kk_list[^" :]*)/g)
ar.forEach(function(val){
console.log(eval("list."+val));
});
OUTPUT
jack
123

How to build this json?

[{"username" : "11"},
{"password" : "test"},
{"detailorder" : [
{"id" : "1",
"qty" : "5"},
{"id" : "2",
"qty" : "10"}
]}
]
How di I create above json in javascript? I have very low understanding in json. I reffered to How do i build JSON dynamically in javascript?. I need to add data dinamically especially for detailorder. But I' stuck from beginning.
I wrote
var datajson = [];
And i dont know how to what to write next. Sorry for my bad english. Thanks
Create the array, assign it to a variable and stringify it.
Here is how:
var arr = [
{ username:'11' },
{ password:'test' },
{ detilpesanan: [
{ id:'1',jumlah:'5' },
{ id:'2',jumlah:'10' }
]}
];
var json = JSON.stringify(arr);
do you mean like:
var datajson = [
{ "username" : 11 },
{"password" : "test"},
{"orderdetail" :
{
"id": 1,
"qty": 25
},
{
"id": 2,
"qty": 10
}
}
];
Added:
var datajson = {};
datajson.username = 11;
datajson.password = "test";
datajson.detilpesanan = [];
datajson.detilpesanan.push({});
datajson.detilpesanan.unshift({});
datajson.detilpesanan[0]["id"] = 1;
datajson.detilpesanan[0]["jumlah"] = 5;
datajson.detilpesanan[1]["id"] = 2;
datajson.detilpesanan[1]["jumlah"] = 10;
console.log( datajson );
I'd like to suggest something to make it easier. First, you will need to use jquery, or any other javascript library that provides json parsing and endcoding. Then create that structure as a standard object on javascript. Use jquery ( or whatever javascript library you chose ), to encode it into a JSON string for you.
I have been using JSON format for years now, but I can barely recall the need to write it down myself. Maybe there were instances, but I think I did not use it for the actual implementation.
You can also go to json.org, and download parsers and encoders available.
I hope that helped.
You can see: http://www.json.org/js.html
JSON (Javascrtip Serialization Object) is a serialization object type, so you cant create objects and then serialize this object, like this:
function createPerson()
{
var persons = new Array();
for(i=0; i<3; i++)
{
var details = new Array();
for(k = 0; k<2;k++)
{
var det = new persondetail(k,k*2);
details.push(det);
}
var p = new person('user'+i,'pdw'+i,details);
persons.push(p);
}
//-- serialize object, see console output
console.log(JSON.stringify(persons));
}
function person(user, pwd,det)
{
this.username = user;
this.password = pwd;
this.detilpesanan = det;
}
function persondetail(id, jumlah)
{
this.id = id;
this.jumlah = jumlah;
}

creating list of objects in Javascript

Is it possible to do create a list of your own objects in Javascript? This is the type of data I want to store :
Date : 12/1/2011 Reading : 3 ID : 20055
Date : 13/1/2011 Reading : 5 ID : 20053
Date : 14/1/2011 Reading : 6 ID : 45652
var list = [
{ date: '12/1/2011', reading: 3, id: 20055 },
{ date: '13/1/2011', reading: 5, id: 20053 },
{ date: '14/1/2011', reading: 6, id: 45652 }
];
and then access it:
alert(list[1].date);
dynamically build list of objects
var listOfObjects = [];
var a = ["car", "bike", "scooter"];
a.forEach(function(entry) {
var singleObj = {};
singleObj['type'] = 'vehicle';
singleObj['value'] = entry;
listOfObjects.push(singleObj);
});
here's a working example http://jsfiddle.net/b9f6Q/2/
see console for output
Maybe you can create an array like this:
var myList = new Array();
myList.push('Hello');
myList.push('bye');
for (var i = 0; i < myList .length; i ++ ){
window.console.log(myList[i]);
}
Going off of tbradley22's answer, but using .map instead:
var a = ["car", "bike", "scooter"];
a.map(function(entry) {
var singleObj = {};
singleObj['type'] = 'vehicle';
singleObj['value'] = entry;
return singleObj;
});
Instantiate the array
list = new Array()
push non-undefined value to the list
var text = list.forEach(function(currentValue, currentIndex, listObj) {
if(currentValue.text !== undefined)
{list.push(currentValue.text)}
});
So, I'm used to using
var nameOfList = new List("objectName", "objectName", "objectName")
This is how it works for me but might be different for you, I recommend to watch some Unity Tutorials on the Scripting API.

Categories

Resources