Reputation: 740
I have an array whose elements are in string format, like this:
somearray = ["abc", "pqr", "xyz"]
I need to create an object from this array whose variable I have declared as var newobject = {}
. 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 named 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?
Upvotes: 1
Views: 166
Reputation: 18997
Just use key-value notation:
var newobject = {};
var somearray = ["abc", "pqr", "xyz"] ;
somearray.forEach(function(x,i){
newobject[i]=x;
})
console.log(newobject);
Upvotes: 0
Reputation: 92854
Simple solution using Array.forEach
and Array.push
functions:
var somearray = ["abc", "pqr", "xyz"], objects = [];
somearray.forEach((v) => objects.push({name: v}) );
console.log(JSON.stringify(objects, 0, 4));
Or the same using Array.map
function:
var somearray = ["abc", "pqr", "xyz"], objects;
objects = somearray.map((v) => ({name: v}) );
The output:
[
{
"name": "abc"
},
{
"name": "pqr"
},
{
"name": "xyz"
}
]
Upvotes: 3