-2

This is my data and I am trying to map the name of the nodes to the sources and targets of the links.

var x = {
  "nodes": [
    {
      "name": "Decision 3a"
    },
    {
      "name": "Req 1"
    },
    {
      "name": "Req 3c"
    },
    {
      "name": "Cloud Services"
    }
  ],
  "links": [
    {
      "source": "0",
      "target": "3",
      "value": 100
    },
    {
      "source": "4",
      "target": "2",
      "value": 100
   }
  ]
};

I want the object to look like this for my visualization--

var x = {
      "nodes": [
        {
          "name": "Decision 3a"
        },
        {
          "name": "Req 3"
        },
        {
          "name": "Req 3c"
        },
        {
          "name": "Req 3b"
        }
      ],
      "links": [
        {
          "source": "Decision 3a",
          "target": "Req 3c",
          "value": 100
        },
        {
          "source": "Cloud Services",
          "target": "Req 1",
          "value": 100
       }
      ]
    };

I tried adding the id to the nodes and then map them but in that case the id remain there in the nodes object.

gkuhu
  • 299
  • 1
  • 4
  • 17
  • 1
    First things first, there is no JSON in this question, that's a Javascript object – Liam Nov 12 '18 at 11:18
  • Possible duplicate of [Access / process (nested) objects, arrays or JSON](https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Liam Nov 12 '18 at 11:19

1 Answers1

0

you need to loop through the each object in the links array and get the index from the nodes array and assign that value to the links array.

i hope the below code solves the issue

var x = {
  "nodes": [
    {
      "name": "Decision 3a"
    },
    {
      "name": "Req 1"
    },
    {
      "name": "Req 3c"
    },
    {
      "name": "Req 4"
    },
    {
      "name": "Cloud Services"
    }
  ],
  "links": [
    {
      "source": "0",
      "target": "3",
      "value": 100
    },
    {
      "source": "4",
      "target": "2",
      "value": 100
   }
  ]
};

x.links.forEach(o => {
 let name = x.nodes[parseInt(o.source)].name;
 o["source"] = name;
})

console.log("output",x)
Learner
  • 8,379
  • 7
  • 44
  • 82