1

I am facing lot of issue to initialize an array of object with a predefined array. I am not being able to copy that array to my new array of objects. If anyone knows it then let me know.

admins is basically an array which contains string items like ["hello","hii","sup",....]

var admins = ["hello","hii","sup"];
var obj = [];

for(var i=0; i<admins.length; i++)
{
    obj[i].name = admins[i];
}

console.log(obj);

"TypeError: Cannot set property 'name' of undefined"

2
  • 1
    What does admins look like? Commented Jun 11, 2019 at 10:44
  • admins is basically an array which contains string items like ["hello","hii","sup",....] Commented Jun 11, 2019 at 10:53

4 Answers 4

6

Use a map:

var newArray = admins.map((admin) => ({ name: admin }));
Sign up to request clarification or add additional context in comments.

1 Comment

after reviewing the question again, this is the best answer +++1
1

IMHO: use spread operator:

const admins = ["John", "Doe", "Duck"];
const obj = [...admins].map(
  (admin) => ({ name: admin })
);
console.log(obj); 

8 Comments

How will this assign name property to each object in the new array?
@UmairSarfraz this is not clear if the OP want to set the name. The title says "initialize from predefined array".
How will I assign the admins values to the name field of the obj array of object??
@MosèRaguzzini Thanks for the edit. However, the spread operator is unnecessary in this case as you are already using a map.
Right, but admins is not an array of objects. It is an array of strings stackoverflow.com/questions/56541905/…
|
-1

Try out this

 var obj = [];

for (var i = 0; i < admins.length; i++) {
  let temp = {};
  temp["name"] = admins[i];
  obj.push(temp);
}

console.log(obj);

Comments

-2

You need to define the obj[i] to empty object (obj[i] = {}).

you are trying to access name property of undefined(obj[i] is undefined in your code).

var obj = [];

    for(var i=0; i<admins.length; i++)
    {
     obj[i] = {
      name: admins[i]
     }
   }

    console.log(obj);

1 Comment

This is the only answer that points to the right concept here which the questioner missed. Each element in the array needs to be an object, only then can one define obj[i].something! Don't know why people down-voted this!

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.