Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of objects javascript

Good afternoon.

I load a json file with information to create a collpsible force layout in D3. I can acess to the data, although i can pass the values into the var links that it is an array of objects, that is responsable to the creation of the visualization. Anyone can help to pass the data from json to var links. The script blow up. I need to create a var links like below where the source is = to the beforePos and target ? afterPos and the type is a string "medium"

var links = [{source: "beforePos", target: "afterPos", type: "medium"},];

Note: The loaded json is huge.

Anyone can help me!

var links = [];
for (i = 0; i < jsonFile.generations.length; i++) {
    for (j = 0; j < jsonFile.generations[i].nodes.length; j++) {
        for (w = 0; w < jsonFile.generations[i].nodes[j].after.stid.length; w++) {
            afterPos = jsonFile.generations[i].nodes[j].after.stid[w];
            beforePos = jsonFile.generations[i].nodes[j].before.stid[w];
            var test = {
                source: beforePos,
                target: afterPos,
                type: "medium"
            };
            links.push(test);
        }
    }
}
like image 484
user2920033 Avatar asked Jan 31 '26 12:01

user2920033


1 Answers

With your description, the best options is to speed process by caching elements.

var links = [];
JG = jsonFile.generations;
for (i = 0, endI = JG.length; i < endI ; i++) {
    JGIN = JG[i].nodes;
    for (j = 0, endJ = JGIN.length ; j < endJ ; j++) {
        JGINJ = JGIN[j];
        JGINJAS=JGINJ.after.stid;
        JGINJBS=JGINJ.before.stid;
        for (w = 0,  endW = JGINJAS.length; w < endW ; w++) {
            links.push({
                source: JGINJAS[w], target: JGINJBS[w], type:"medium"
            });
        }
    }
}

This reduce the needed time, but does not avoid the creation of the array of i*j*w objects.

Best option should be to change the code that manages the array, so it uses a callback to get the element, and use this callback to dinamically determine the element in the json hierarchy that is required.

like image 130
MC ND Avatar answered Feb 02 '26 04:02

MC ND