2

I'm looking for a way to push an array into an object.

Chek this out:

var playlists = {
  playlist01: [],
  playlist02: [],
  playlist03: []
};

Now I need to push a new array, named "playlist04", but I don't know the name, I have it in a var name.

Something like this: playlists.push($foo: []);

Can anyone help me?

Thank you and greetings!

2
  • 2
    playlists[variablename] = []; Commented May 6, 2016 at 20:58
  • the original question didn't get the answer either; even though they are similar the problem in this one is by far more specific and it's answer is definitely "no", i.e.: 'you can not!'. You can't use the array push method on Object, and you cannot extract the name of a variable. Commented May 6, 2016 at 21:21

1 Answer 1

5

You push things into arrays. You add properties to objects. It's as simple as this:

playlists.playlist04 = [];

Or if I'm interpreting your latter code correctly, like this:

playlists.playlist04 = $foo;

Or if you don't know the name that you want for the property but you have that name stored in a variable, you can use bracket notation:

playlists[$foo] = [];
Sign up to request clarification or add additional context in comments.

2 Comments

I think the property name is unknown in his case, might want to add code similar to Jerry's comment.
@IrkenInvader Good point. Added it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.