简体   繁体   中英

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?

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.

If you want to use the new ES6 syntactic sugar. It looks like you can do something like this:

this.Edges = {};

var path = 'the_path',
    edgeDst = 'edgeDst',
    edgeSrc = 'edgeSrc';

this.Edges[path] = { edgeDst, edgeSrc };

console.log(this.Edges) => {edgeDs:"AND_m_5",edgeSrc:"edgeSrc"} 

Here is a link to a functioning example: https://jsfiddle.net/xwf3wadr/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM