73

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 }
Liam
  • 27,717
  • 28
  • 128
  • 190
Mike
  • 12,359
  • 17
  • 65
  • 86
  • 2
    Do you also need code to produce the final JSON? – orangepips Nov 01 '10 at 18:15
  • possible duplicate of [Using a variable for a Javascript object key](http://stackoverflow.com/questions/2274242/using-a-variable-for-a-javascript-object-key) – Bergi Jul 24 '13 at 17:39

8 Answers8

211

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.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • This would work fine but my names are also variables. So when the name changes it overwrites the previous name value pair. – Mike Nov 01 '10 at 18:07
  • @Mike: You can use a variable to specify the name of the property. It's the value of the variable at the moment of accessing the object that decides what property is accessed, so changing the variable to a different string between accesses is not a problem. See my addition above. – Guffa Nov 01 '10 at 18:20
  • Well, I am using a .change function to generate this and for some reason it keeps overwriting my name. Is there anyway to temporarily deference the variable? – Mike Nov 01 '10 at 18:29
  • Post code for the .change function and we can better help you. – orangepips Nov 01 '10 at 18:37
  • http://pastie.org/1264618 as I mentioned, it only allows for one name value pair... – Mike Nov 01 '10 at 18:40
  • Setting one property doesn't overwrite another property. The likely reason is that you are creating a new object each time which replaces the previous, so that it only has the latest property in it. – Guffa Nov 01 '10 at 18:44
  • yes, that is precisely what is happening. See my pastie. Do you see anyway around that? – Mike Nov 01 '10 at 18:49
  • @Mike: You can check if the object already exist, so that you only create one the first time: http://pastie.org/1264654 – Guffa Nov 01 '10 at 18:55
36

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' 
           }
Dylan Hogg
  • 3,118
  • 29
  • 26
  • Nice Solution and working. let dataToUpdate = { [field]: body[field], }; To update specific field and its value – Ashok Dec 08 '22 at 09:49
8

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

Max
  • 454
  • 4
  • 10
5

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;
}
orangepips
  • 9,891
  • 6
  • 33
  • 57
3

in Javascript.

    var myObject = { "name" : "john" };
    // { "name" : "john" };
    myObject.gender = "male";
    // { "name" : "john", "gender":"male"};
Atif Hussain
  • 880
  • 12
  • 19
3

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"
  }
}
Hamzeen Hameem
  • 2,360
  • 1
  • 27
  • 28
1

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}
0

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/lodash@4.17.10/lodash.min.js"></script>
Penny Liu
  • 15,447
  • 5
  • 79
  • 98