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?
-
2I think you might be confusing JSON with Javascript.mikerobi– mikerobi2010年11月01日 17:13:35 +00:00Commented Nov 1, 2010 at 17:13
-
JSON is javascript. I am just wondering how to add values to my object dynamically.Mike– Mike2010年11月01日 17:15:23 +00:00Commented Nov 1, 2010 at 17:15
-
6JSON is not Javascript, JSON is a data format. The sample above would trigger an error in any standards complient JSON parser.mikerobi– mikerobi2010年11月01日 17:22:39 +00:00Commented Nov 1, 2010 at 17:22
-
2@mikerobi JSON stands for Javascript Object Notation, so I would say it's Javascript.Waleed Khan– Waleed Khan2012年07月18日 02:58:36 +00:00Commented Jul 18, 2012 at 2:58
-
7@WaleedKhan JSON has it's roots in JS, but it is not JS any more. Take a look at json.org it's used in other languages now, and is only a specification on how to structure data. Saying JSON is JavaScript because it has JavaScript in the name is like saying JavaScript is Java b/c it has Java in it's name...patrickgamer– patrickgamer2013年01月06日 18:09:48 +00:00Commented Jan 6, 2013 at 18:09
4 Answers 4
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;
Comments
var ipID = {};
ipID.name = 'val';
ipID.anotherName = 'anotherVal';
1 Comment
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.
Comments
Solution For JSON Object:
By default:
array=[];
object={};
JSON Code:
var People= {};
Json.People[key]="value";
JSON Result:
{People:
{
key: "value"
}
}