开发者

Assigning objects to keys inside a JavaScript object

开发者 https://www.devze.com 2023-03-11 22:39 出处:网络
I want to create an object like this: var servers = { \'local1\' : { name: \'local1\', ip: \'10.10.10.1\' },

I want to create an object like this:

var servers = 
{
  'local1' :
  {
    name: 'local1',
    ip: '10.10.10.1'
  },
  'local2' :
  {
    name: 'local2',
    ip: '10.10.10.2'
  }
}

This is what I'm doing

$.each( 开发者_如何学Cservers, function( key, server )
{
    servers[server.name] = server;
});

Where servers is an array of objects like these:

{
    name: 'local1',
    ip: '10.10.10.1'
}

But the code above does not assign any keys to the object, so the keys default to 0,1,2....


One potential bug I notice is that you're modifying the object that you are iterating over (servers). It might be good to create a new empty object that you modify in the loop.

Also, it'd help if you posted some sample data so we can run your code for ourselves.

Finally, you could try inserting a debugger keyword in there and stepping through the code.


In Chrome if You run this:

a = [];
b = {n:"c",i:"1.2.3.4"};
a[b.n] = b;
alert (a["c"].i);
alert (a.c.i);

You will got the "1.2.3.4" string as expected. But if you change the example as:

a = {};
b = {n:"c",i:"1.2.3.4"};
a[b.n] = b;
alert (a.c.i);

You will get the same "1.2.3.4" again :). So the answer is: your code assigns the properties to the objects as you asked. The only difference is that in the first example you used the array as object, and in second the simple object.


AFAIK [] in javascript is used to index arrays, while to access object properties you have to use dot notation. So your code should be:

$.each( servers, function( key, server )
{
    var name = server.name;
    eval("servers." + name + "  = server");
});

Please try it out since I don't test it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号