faia20 faia20 - 6 months ago 11
JSON Question

How do I translate javascript object to a new object?

I need to import a few external json data into a variable or into a single json file to then display that data with D3.

This is the format of the data that I need to import from each json file:

{
"name": "name1",
"version": "0.1.2",

"references": [
{
"url1": "http://example1.com"
},
{
"url2": "http://example2.com"
}
]
}


And this is the format of data that I need for the final json file/variable.

{
"nodes":[
{
"name": "name1",
"version": "0.1.2",
"references": [
{
"url1": "http://example1.com"
},
{
"url2": "http://example2.com""
}
]
},

{
"name": "name2",
"version": "1.6.0",
"references": [
{
"url1": "http://example34.com"
},
{
"url2": "http://example30.com""
}
]
},
{
...
...
}
],
"links":[
]
}


Basically I need to merge the data from the different json files inside the "nodes" array.

Any idea how could I do this?
Thanks

Answer

nodes is a simple array, so you can just push the 'file' objects into the nodes array.

var file1 = {
    "name": "name1",
    "version": "0.1.2",
    "references": [
        {
            "url1": "http://example1.com"
        },
        {
            "url2": "http://example2.com"
        }
    ]
}

var file2 = {
    "name": "name1",
    "version": "0.1.2",
    "references": [
        {
            "url1": "http://example1.com"
        },
        {
            "url2": "http://example2.com"
        }
    ]
}

var files = [file1, file2];

var node = {
    "nodes": [],
    "links": []
}

files.forEach(function(file) {
    node.nodes.push(file);
})

console.log(node);