1

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?

5
  • 1
    What exactly are you trying to achieve? An object always has a key for each value. Commented Jun 18, 2016 at 19:14
  • What do you want as the keys and values of the object? Commented Jun 18, 2016 at 19:15
  • Please show us how the expected result is supposed to look (as JSON) Commented Jun 18, 2016 at 19:21
  • Expected output is [object, object, object] where each object is {name: "abc/pqr/xyz"} Commented Jun 18, 2016 at 19:26
  • var result = somearray.map(function(str, i) { return {name: str} }) Commented Jun 18, 2016 at 19:27

2 Answers 2

3

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"
    }
]
Sign up to request clarification or add additional context in comments.

Comments

0

Just use key-value notation:

var newobject = {};
var somearray = ["abc", "pqr", "xyz"] ;
somearray.forEach(function(x,i){
  newobject[i]=x;
})
console.log(newobject);

5 Comments

Why use .map()? You're just throwing away the resulting Array of undefined. Either .forEach() or .reduce() would make more sense.
@squint Are you very much worried about the thrown array? I use it because it's shorter...
yes it could have been done like newObj = somearray.reduce((p,c,i) => (p[i] = c,p),{});
@nicael: Are you very much worried about 4 more characters? Constructing, populating and discarding an array without using it at all is a very strange thing to do intentionally.
@nicael of course it will effect performance, your creating an array and then throwing it away for no reason. You don't get that for free.

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.