shanky singh shanky singh - 4 years ago 109
Javascript Question

How to create object dynamically

I am new in Javascript. I want to create array of dynamic object. Here for example

I have an array of constructor in which I am getting some value. In my constructor MyItms have some attributes like value and property. I want to make an object by assigning or mapping to property

var Item = MyItems;
for(var i=0; i<MyItems.length; i++){
var Values = MyItems[i]._value; // Car is my value here
var prop = MyItems[i]._property; // Name
var obj ={
prop : Values

But In this case obj is returning value like

`prop : car`,

What I am expecting here is
Name : Car

Also I want array of objects for all
Any way to get this.
Thanks in advance.

Answer Source

In newer JS, you can write this (note the square brackets):

var obj = {
    [prop]: Values

In older JS this is not available, you would need to do this (still works in new JS as well):

var obj = {};
obj[prop] = Values;

If you want an array of objects as a result, you can initialise an empty array at top:

var objs = [];

and then push each obj into it:


Alternately, and more readably, you can use the map function:

var objs = {
  return resultObj;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download