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?

6
  • You already did that. Commented Mar 10, 2017 at 12:32
  • 1
    Just do ObjectNames.labels = name; Commented Mar 10, 2017 at 12:33
  • What you show works. You could also just have used labels : name inside the object unless you want to clone everything. Commented Mar 10, 2017 at 12:33
  • 1
    Do labels: [...name] Commented Mar 10, 2017 at 12:36
  • ObjectNames.labels = name.slice();. Commented Mar 10, 2017 at 12:36

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Or just slice(). No argument required
@Andrew Yes, I just realized that, thanks for clarifying. I've never been sure about when Javascript makes a copy and when it doesn't
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);

Comments

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))

1 Comment

i want to do this with a for loop not like that

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.