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!

Jaco Treus
  • 75
  • 1
  • 9
  • 2
    `playlists[variablename] = [];` –  May 06 '16 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. – Bekim Bacaj May 06 '16 at 21:21

1 Answers1

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] = [];
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91