简体   繁体   English

动态添加到Javascript对象

[英]Dynamically Add to Javascript Object

I have a Javascript object that looks like this. 我有一个看起来像这样的Javascript对象。

ips[ipID] = {}

So I end up with a bunch of ips that need to store information that will look like 所以我最终得到了一堆需要存储看起来像的信息的ips

ipID { name : 'val', anotherName : 'anotherVal' }

My question is, how do I dynamically add these names and values? 我的问题是,如何动态添加这些名称和值?

I believe this is the easiest thing to do if your names are dynamic: 我相信如果你的名字是动态的,这是最简单的事情:

var myobj = {};
var newFieldName = 'my new field name';
var newFieldValue = 'my new field value';
myobj[newFieldName] = newFieldValue;
var ipID = {};
ipID.name = 'val';
ipID.anotherName = 'anotherVal';

If you would like to use the great underscore library (a swiss army knife for js developers), you could use the extend method http://documentcloud.github.com/underscore/#extend . 如果你想使用伟大的下划线库(js开发人员的瑞士军刀),你可以使用扩展方法http://documentcloud.github.com/underscore/#extend

So for example 所以举个例子

var tmp = { name: "asdf", val: "value" };
_(ips[ipID]).extend(tmp);

Hope this is clear, it would be easier to help if you had a more precise question. 希望这很清楚,如果你有一个更精确的问题,它会更容易帮助。

Solution For JSON Object: JSON对象的解决方案:

By default: 默认情况下:

array=[];
object={};

JSON Code: JSON代码:

var People= {};

Json.People[key]="value";

JSON Result: JSON结果:

{People: 
      {
        key: "value"
      }
}

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

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