Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically Add Variable Name Value Pairs to JSON Object

I have a json object full of ips like

var ips = {} 

I then add ip objects to this object like so

ips[ipID] = {} 

I then need to add dynamic/variable name value pairs to each ip so I am using code like this

var name; var value; var temp = {}; tmp[name] = value 

My question is, how can I add these name value pairs/ tmp to my ipID objects so that my outcome turns out like

ipID = { name : value, anotherName : anotherValue } 
like image 909
Mike Avatar asked Nov 01 '10 17:11

Mike


People also ask

How do you add a key-value pair in an object dynamically?

To add dynamic key-value pairs to a JavaScript array or hash table, we can use computed key names. const obj = {}; obj[name] = val; to add a property with the value of name string as the property name. We assign val to as the property's value.

How do I add data to an existing JSON object?

Use push() method to add JSON object to existing JSON array in JavaScript. Just do it with proper array of objects .

Can you put variables in JSON?

Variables provide a new way to tackle different scenarios where JSON schema alone fails. This means, that you can use a new keyword named $vars to make your life easier.


1 Answers

That's not JSON. It's just Javascript objects, and has nothing at all to do with JSON.

You can use brackets to set the properties dynamically. Example:

var obj = {}; obj['name'] = value; obj['anotherName'] = anotherValue; 

This gives exactly the same as creating the object with an object literal like this:

var obj = { name : value, anotherName : anotherValue }; 

If you have already added the object to the ips collection, you use one pair of brackets to access the object in the collection, and another pair to access the propery in the object:

ips[ipId] = {}; ips[ipId]['name'] = value; ips[ipId]['anotherName'] = anotherValue; 

Notice similarity with the code above, but that you are just using ips[ipId] instead of obj.

You can also get a reference to the object back from the collection, and use that to access the object while it remains in the collection:

ips[ipId] = {}; var obj = ips[ipId]; obj['name'] = value; obj['anotherName'] = anotherValue; 

You can use string variables to specify the names of the properties:

var name = 'name'; obj[name] = value; name = 'anotherName'; obj[name] = anotherValue; 

It's value of the variable (the string) that identifies the property, so while you use obj[name] for both properties in the code above, it's the string in the variable at the moment that you access it that determines what property will be accessed.

like image 75
Guffa Avatar answered Sep 28 '22 03:09

Guffa