lundi 1 août 2016

How to create an array of objects from an existing array in javascript?

I have an array whose elements are in string format. It is like this: somearray = ["abc", "pqr", "xyz"] Now I need to create an object from this array whose variable I have declared as var newobject = {} Now, I tried this:

var newobject = {};
var index = 0;
somearray.forEach(function() {
newobj = {
    name : somearray[index]
};``
index++;
});

This does create an object but only consisting of the last string in the array (somearray)

If instead of

newobj = {
        name : somearray[index]
    };

I write

newobj[index] = {
        name : somearray[index]
    };

the objects are names as 0,1,2. I don't want this to happen, nor do I want anything else in its place. Isn't there any way like how we use push method for arrays?

Aucun commentaire:

Enregistrer un commentaire