cybodroid cybodroid - 1 year ago 56
Javascript Question

How to add a set values for key to Javascript objects?

I have following javascript variable:

this.Edges = {};

Then I did

this.Edges[path] = {edgeDst};

So Edges variable at this point is somehing like

Edges['232kb32i23'] = { edgeDst: 'AND_m_5' }

after that I when I did

this.Edges[path] = {edgeSrc};

It overwrote the value I had added with edgeDst.
At this point Edges is like following:

Edges['232kb32i23'] = { edgeSrc: 'B_m_5' }

But I want to produce something like:
Edges['232kb32i23'] = { edgeDst: 'AND_m_5', edgeSrc: 'B_m_5' }

Here I can't added edgeSrc and edgeDst simulataneously.

How will I achieve this?

Answer Source

You can use the following:

var Edges = {};                  // these are just so that you can run the snippet
var path = '232kb32i23';

Edges[path] = {};                // set Edges[path] to a new object
Edges[path].edgeDst = 'AND_m_5'; // set the edgeDst property on Edges[path]
Edges[path].edgeSrc = 'B_m_5';   // set the edgeSrc property on Edges[path]

console.log(Edges);              // run the snippet to see the result

You will have to modify the code to use this for your application, but I tried to make as succinct an example as possible.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download