0

I'm trying to create an object where there is a key value pair, and the value is an array.

i.e:

foo = {'key1':['val1','val2'], 'key2':['v3','v4']};

Is this possible in pure JS?

e.g.

var foo = {};
foo['key1'] = ['keyOneVal1'];
foo['key1'] = ['keyOneVal2'];

but as you may have guessed, this just overwrites the keyOneVal1.

I've also tried

var foo = {};
foo['key1'].push('k1v1');
foo['key1'].push('k1v2');

but couldn't get it working in a jsfiddle.

EDIT:

Okay heard you guys loud and clear. This object will not be initialized with an starting key, it's dynamically inserted based on time. So in the end the object will look more like

foo = {'time1':['a','b'], 'time2':['c','d','e','f'], 'time3':['y','y']};
2
  • Are you trying to do it dynamically? Your "example" is perfectly valid. Commented Dec 16, 2014 at 20:49
  • Also, check the errors in the console. Commented Dec 16, 2014 at 20:50

3 Answers 3

6

It's very possible. Your second example is the correct way to do it. You're just missing the initializer:

var foo = {};
foo['key1'] = [];
foo['key1'].push('k1v1');
foo['key1'].push('k1v2');

for(var i = 0; i < foo['key1'].length; i++) {
  document.write(foo['key1'][i] + '<br />');
}

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

3 Comments

You need the initializer because foo['key1'] isn't an array. It's undefined until you initialize it as an empty array.
and what's this so ? foo = {'key1':['val1','val2'], 'key2':['v3','v4']};
@Bhojendra-C-LinkNepal - That's the result that the OP is hoping to get as a result of their statements, not the starting point.
2

Try something like this make sure you declare key1:

var foo = {"key1" : []};
foo['key1'].push('k1v1');
foo['key1'].push('k1v2');

Comments

1

It can be done like this

var foo = {"key":[]}
foo["key"].push("val1")
foo["key"].push("val2")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.