32

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?

5
  • 2
    I think you might be confusing JSON with Javascript. Commented Nov 1, 2010 at 17:13
  • JSON is javascript. I am just wondering how to add values to my object dynamically. Commented Nov 1, 2010 at 17:15
  • 6
    JSON is not Javascript, JSON is a data format. The sample above would trigger an error in any standards complient JSON parser. Commented Nov 1, 2010 at 17:22
  • 2
    @mikerobi JSON stands for Javascript Object Notation, so I would say it's Javascript. Commented 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... Commented Jan 6, 2013 at 18:09

4 Answers 4

48

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;
Sign up to request clarification or add additional context in comments.

Comments

27
var ipID = {};
ipID.name = 'val';
ipID.anotherName = 'anotherVal';

1 Comment

Ok that works. I guess I should have mentioned that my names and values are both dynamic. So I am using tmp[name] = value; and then I need to add tmp.
5

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

0

Solution For JSON Object:

By default:

array=[];
object={};

JSON Code:

var People= {};

Json.People[key]="value";

JSON Result:

{People: 
      {
        key: "value"
      }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.