Dynamically Add to Javascript Object

后端 未结 4 1731
面向向阳花
面向向阳花 2020-12-09 14:56

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 li

相关标签:
4条回答
  • 2020-12-09 15:34
    var ipID = {};
    ipID.name = 'val';
    ipID.anotherName = 'anotherVal';
    
    0 讨论(0)
  • 2020-12-09 15:37

    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.

    0 讨论(0)
  • 2020-12-09 15:46

    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;
    
    0 讨论(0)
  • 2020-12-09 15:46

    Solution For JSON Object:

    By default:

    array=[];
    object={};
    

    JSON Code:

    var People= {};
    
    Json.People[key]="value";
    

    JSON Result:

    {People: 
          {
            key: "value"
          }
    }
    
    0 讨论(0)
提交回复
热议问题