【问题标题】:How do I translate javascript object to a new object?如何将 javascript 对象转换为新对象?
【发布时间】:2016-06-01 09:28:10
【问题描述】:

我需要将一些外部 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":[
      ]
    }

基本上我需要在“nodes”数组中合并来自不同json文件的数据。

知道我该怎么做吗? 谢谢

【问题讨论】:

  • 我不认为这是在重复那个话题,我认为他真正想要的是如何将多个 JSON 文件合并为一个......?
  • 不完全是重复的......这里的OP问题是不同的。
  • 你的权利,不是骗子。太好了……你试过什么?任何事物? x 如何转换为 y 也不清楚
  • 不确定你到底在寻找什么 OP,但你不能把它们推送到一个 JS 对象吗? stackoverflow.com/questions/21450060/…
  • 现在我同意复制。

标签: javascript json d3.js


【解决方案1】:

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

【讨论】:

  • 谢谢马克!我认为这应该对我有用!我现在就试一试。
【解决方案2】:

如果您只需要将导入的 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/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-14
    • 2015-12-10
    • 2021-10-01
    • 1970-01-01
    • 2022-08-18
    • 2016-12-26
    相关资源
    最近更新 更多