0

i'm new to javascript and i have a little issue. I have an array like this:

name = ["Alex","John", "Mark"].

After that, i have and object with an array inside like this:

ObjectNames = {
  labels: []
}

I want to fill the labels array with the content of tha name array like this:

labels = [name[0], name[1], name[2]]

How to do this?

RamAlx
  • 6,976
  • 23
  • 58
  • 106

3 Answers3

3

What you did in your question already solves your problem, but you can try this:

ObjectNames = {
    labels: names
}

This will make a copy of names and store it in labels.

Let me know if it works

Edit: As Andrew Li pointed out, there's no need to use slice, as JavaScript automatically creates a copy

Larpee
  • 800
  • 1
  • 7
  • 18
2

You could do it like this :

var _name = ["Alex","John", "Mark"];
var ObjectNames = {
  labels: []
};
_name.forEach(function(e) {
  ObjectNames.labels.push(e);
});
console.log(ObjectNames.labels);
m87
  • 4,445
  • 3
  • 16
  • 31
1

There are lots of way you can do that

Try like this

var ObjectNames = {
  labels: [name[0], name[1], name[2]]
}

or

var ObjectNames = {
  labels: name
}

or

var ObjectNames = {
  labels: name.slice()
}

or

ObjectNames = {
  labels: []
}

ObjectNames.labels=name ;

or like this

for(var i=0;i<name.length;i++)
  ObjectNames.labels.push(name[i])

or

name.forEach(x=> ObjectNames.labels.push(x))
Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80