shanky singh
shanky singh

Reputation: 1141

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 MyItems Any way to get this. Thanks in advance.

Upvotes: 2

Views: 6613

Answers (1)

Amadan
Amadan

Reputation: 198314

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:

objs.push(obj);

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

var objs = MyItems.map(function(item) {
  ...
  return resultObj;
});

Upvotes: 11

Related Questions