How to add javascript object to another object in dynamic

Suppose I have several javascript objects

{"type":"gotopage","target":"undefined"}
{"type":"press","target":"a"}
{"type":"rotate","target":"long"}

How to add these objects to another object, for example

config={}

I know how to do it if each inserted object has an id, which I can add as:

config["id"]={}

But in this case, how to add objects without id?

+5
source share
5 answers

I think you are mixing objects and arrays. Objects have named keys, arrays have numeric keys. You can easily add to the array with .push():

var arr = [];
arr.push("something");

However, for the configuration object, since your variable name suggests that this is not very useful. You are better off using meaningful names for your parameters, for example:

var config = {
    something: 'blah',
    foo: 'bar'
};

You can also save the array in your object:

config.manyStuff = [];
for(...) {
    manyStuff.push(...);
}
+6
var obj1 = {"type":"gotopage","target":"undefined"};

var config = {};
config.obj1 = obj1;

.

var obj1 = {"type":"gotopage","target":"undefined"};

var config = {};
config.obj1 = obj1;

var obj2 = {"key":"data"};
config.obj2 = obj2;
+10

If this data is of the same type, use an array instead:

var some_data = {"type":"gotopage","target":"undefined"}

var config = [];
var config.push(some_data); //and do this for the rest

And you can access the configuration items as follows:

var someVariable = config[index]; //where index is a number starting from 0
+1
source

If you want to add them during the initialization, this can help you:

 var config = [
               {"type":"gotopage","target":"undefined"},
               {"type":"press","target":"a"},
               {"type":"rotate","target":"long"}
              ]
0
source

I use this utility function:

module.exports.combine = function() {

  var rv = {};
  for (i = 0; i < arguments.length; i++) {
    for (thing in arguments[i]) {
        rv[thing]=arguments[i][thing];
    }
  }
  return rv;
}

Properties with the same name will be overwritten by properties in subsequent arguments

var util = require('lib/util.js');
console.log(util.combine(
  {"1":"one","two":function(){;},
  {"four":{"four.5":"four.5-b"}, "5":"foo"}});

result:

    { '1': 'one',
    '5': 'foo',
    two: [Function],
    four: { 'four.5': 'four.5-b' } }
0
source

All Articles