簡體   English   中英

如何將javascript對象轉換為新對象?

[英]How do I translate javascript object to a new object?

我需要將一些外部json數據導入到變量或單個json文件中,然后使用D3顯示該數據。

這是我需要從每個json文件導入的數據格式:

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

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

這是最終json文件/變量所需的數據格式。

    {
      "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":[
      ]
    }

基本上,我需要合並“節點”數組中不同json文件中的數據。

知道我該怎么做嗎? 謝謝

nodes是一個簡單的數組,因此您可以將“文件”對象推入nodes數組。

 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); 

如果僅需要將所有數據從導入的JSON推送到nodes ,則可以執行以下操作:

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

var finalJson = {
    nodes: []
};

finalJson.nodes.push(imported);

這是小提琴: https : //jsfiddle.net/vj1nqeu5/1/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM