简体   繁体   English

如何为Javascript对象添加键的设置值?

[英]How to add a set values for key to Javascript objects?

I have following javascript variable: 我有以下javascript变量:

this.Edges = {};

Then I did 然后我做了

this.Edges[path] = {edgeDst};

So Edges variable at this point is somehing like 所以此时Edges变量有点像

Edges['232kb32i23'] = { edgeDst: 'AND_m_5' } 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. 它覆盖了我用edgeDst添加的值。 At this point Edges is like following: 此时Edges如下所示:

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

But I want to produce something like: Edges['232kb32i23'] = { edgeDst: 'AND_m_5', edgeSrc: 'B_m_5' } 但我想生成类似以下内容的代码: Edges ['232kb32i23'] = {edgeDst:'AND_m_5',edgeSrc:'B_m_5'}

Here I can't added edgeSrc and edgeDst simulataneously. 在这里,我无法同时添加edgeSrc和edgeDst。

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. 您将不得不修改代码以将this用于您的应用程序,但是我尝试尽可能简洁地举例说明。

If you want to use the new ES6 syntactic sugar. 如果要使用新的ES6语法糖。 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/ 这是一个功能示例的链接: https : //jsfiddle.net/xwf3wadr/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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