46

Basically I want to create one large object of many object in JavaScript. Something like:

var objects = {}
for (x)
objects.x = {name: etc}

Any ideas?

3
  • 1
    This is very confusing. Answer this: What are you looping over and what is your intended result. State your input and your desired output. Commented Mar 4, 2010 at 23:29
  • It might be just me, but I don't get it... Commented Mar 4, 2010 at 23:29
  • This question relates to my other question here: stackoverflow.com/questions/2375143/… I tried passing it as an array of objects but its somehow not working, so I'm trying this method. Something like: ManyObjects: { Object1 : {name:etc, x:etc}, Object2 : {name:etc, x:etc}} Commented Mar 4, 2010 at 23:55

7 Answers 7

95
var objects = {};

for (var x = 0; x < 100; x++) {
  objects[x] = {name: etc};
}
Sign up to request clarification or add additional context in comments.

Comments

16

An actual implementation

Populate a container object with 100 other objects.

<script>
var container = { }; // main object

// add 100 sub-object values
for(i = 0; i < 100; ++i) {
 container['prop'+i ]  /*property name or key of choice*/
         = { 'a':'something', 
             'b':'somethingelse', 
             'c': 2 * i
           }; 
}

TEST THE Results - iterate and display objects...

for(var p in container) {
 var innerObj = container[p];
 document.write('<div>container.' + p + ':' + innerObj + '</div>');
 // write out properties of inner object
 document.write('<div> .a: ' + innerObj['a'] + '</div>');
 document.write('<div> .b: ' + innerObj['b'] + '</div>');
 document.write('<div> .c: ' + innerObj['c'] + '</div>');
}
</script>

Output is like

container.prop0:[object Object]
.a: something
.b: somethingelse
.c: 0
container.prop1:[object Object]
.a: something
.b: somethingelse
.c: 2
container.prop2:[object Object]
.a: something
.b: somethingelse
.c: 4

etc...

Comments

9

Using object[propertyname] is the same as using object.propertyname and hence we can dynamically create object keys with object[propertyname] format
for eg:

var fruits = ["Apple", "Orange", "Banana","Grapes"];
var colors = ["red", "Orange", "yellow","blue"];
var newObj = {};
for (var i = 0; i < fruits.length; i++) {
  newObj[fruits[i]] = colors[i];
}
console.log(newObj);

Comments

7

Try this

var objects = new Array();
var howmany = 10;

for (var i = 0; i < howmany; i++)
{
    objects[i] = new Object();

}

2 Comments

You have a leaking global i variable. Don't forget to use var.
Do not use new Array() and new Object() as it is not efficient performance wise. Instead use the literals.
1

//On Nested Obj like that
var playersCount = {
    "Players" : {}
}

var exempleCount = 5;

for(i=0; i <= exempleCount;i++){
    var BadID = Math.floor(Math.random() * 10000);
  
        playersCount.Players["Player_"+i] = {
            "id":BadID, 
            "xPos":0, 
            "yPos":0, 
            "zPos":0
        };
    }
  console.log(playersCount);

Comments

0

Reusable approach for creation dynamic object

const text = ["Cherries", "Strawberry", "Banana"];
const emoji = ["🍒", "🍓", "🍌"];

const createDynamicObj = (keys, values) => {
  if(!keys || !values) return
  let newObj = {};

  for (let i = 0; i < keys.length; i++) {
    newObj[keys[i]] = values[i];
  }
  return newObj
}


console.log(
  createDynamicObj(emoji, text)
)

Comments

0

I use the following simple function:

function mapObject(array, cb, initial = {}) {
    const obj = initial;

    array.forEach((item, index) => cb(obj, item, index));

    return obj;
}

// js example
console.log('new object:', mapObject(['a', 'b', 'c'], (obj, key, i) => obj[key] = i * 2));

Or better with typescript version:

function mapObject<O extends object, T>(array: T[], cb: (obj: O, item: T, index: number) => void, initial = {} as O): O {
    const obj = initial;

    array.forEach((item, index) => cb(obj, item, index));

    return obj;
}

// ts example
console.log('new object:', mapObject<{ total: number }, number>([1, 2, 3], (obj, num) => {
    obj.total += num;
}, { total: 0 }));

If you have error for eslint rule no-param-reassign - just put to rules: 'no-param-reassign': ['error', { props: false }]

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.