cybodroid cybodroid - 25 days ago 6
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

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
console.log(Edges['232kb32i23']);

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

Comments