Dynamically Add Variable Name Value Pairs to JSON Object

JavascriptObjectObject Literal

Javascript Problem Overview


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 }

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

With ECMAScript 6 there is a better way.

You can use computed property names in object property definitions, for example:

var name1 = 'John'; 
var value1 = '42'; 
var name2 = 'Sarah'; 
var value2 = '35';

var ipID = { 
             [name1] : value1, 
             [name2] : value2 
           }

This is equivalent to the following, where you have variables for the property names.

var ipID = { 
             John: '42', 
             Sarah: '35' 
           }

Solution 3 - Javascript

when using javascript objects, you can also just use "dot notation" to add an item, (which JSLint prefers)

var myArray = { name : "john" };
//will initiate a key-value array with one item "name" and the value "john"
myArray.lastName = "smith";
//will add a key named lastName with the value "smith"
//Object {name: "john", lastName: "smith"}

Here is a screenshot from testing in the Chrome console

screenshot

Solution 4 - Javascript

I'm assuming each entry in "ips" can have multiple name value pairs - so it's nested. You can achieve this data structure as such:

var ips = {}

function addIpId(ipID, name, value) {
	if (!ips[ipID]) ip[ipID] = {};
	var entries = ip[ipID];
	// you could add a check to ensure the name-value par's not already defined here
	var entries[name] = value;
}

Solution 5 - Javascript

in Javascript.

	var myObject = { "name" : "john" };
	// { "name" : "john" };
	myObject.gender = "male";
	// { "name" : "john", "gender":"male"};

Solution 6 - Javascript

if my understanding of your initial JSON is correct, either of these solutions might help you loop through all ip ids & assign each one, a new object.

// initial JSON
var ips = {ipId1: {}, ipId2: {}};

// Solution1
Object.keys(ips).forEach(function(key) {
  ips[key] = {name: 'value', anotherName: 'another value'};
});

// Solution 2
Object.keys(ips).forEach(function(key) {
  Object.assign(ips[key],{name: 'value', anotherName: 'another value'});
});

To confirm:

console.log(JSON.stringify(ips, null, 2));

The above statement spits:

{
  "ipId1": {
    "name":"value",
    "anotherName":"another value"
  },
  "ipId2": {
    "name":"value",
    "anotherName":"another value"
  }
}

Solution 7 - Javascript

From what the other answers have proposed, I believe this might help:

var object = ips[ipId];
var name = "Joe";
var anothername = "Fred";
var value = "Thingy";
var anothervalue = "Fingy";
object[name] = value;
object[anothername] = anothervalue;

However, this is not tested, just an assumption based on the constant repetition of:

object["string"] = value;
//object = {string: value}

Solution 8 - Javascript

You can achieve this using Lodash _.assign function.

var ipID = {};
_.assign(ipID, {'name': "value"}, {'anotherName': "anotherValue"});
console.log(ipID);

<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMikeView Question on Stackoverflow
Solution 1 - JavascriptGuffaView Answer on Stackoverflow
Solution 2 - JavascriptDylan HoggView Answer on Stackoverflow
Solution 3 - JavascriptMaxView Answer on Stackoverflow
Solution 4 - JavascriptorangepipsView Answer on Stackoverflow
Solution 5 - JavascriptAtif HussainView Answer on Stackoverflow
Solution 6 - JavascriptHamzeen HameemView Answer on Stackoverflow
Solution 7 - Javascriptuser4953229View Answer on Stackoverflow
Solution 8 - JavascriptPenny LiuView Answer on Stackoverflow