Dynamically Add to Javascript Object

2020-02-05 01:45发布

I have a Javascript object that looks like this.

ips[ipID] = {}

So I end up with a bunch of ips that need to store information that will look like

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

My question is, how do I dynamically add these names and values?

4条回答
小情绪 Triste *
2楼-- · 2020-02-05 01:50

Solution For JSON Object:

By default:

array=[];
object={};

JSON Code:

var People= {};

Json.People[key]="value";

JSON Result:

{People: 
      {
        key: "value"
      }
}
查看更多
▲ chillily
3楼-- · 2020-02-05 02:06

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.

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.

查看更多
beautiful°
4楼-- · 2020-02-05 02:08
var ipID = {};
ipID.name = 'val';
ipID.anotherName = 'anotherVal';
查看更多
我只想做你的唯一
5楼-- · 2020-02-05 02:09

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;
查看更多
登录 后发表回答