简体   繁体   中英

Javascript - object with key value pair, where value is an array

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

ie:

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

Is this possible in pure JS?

eg

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']};

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 />'); } 

Try something like this make sure you declare key1:

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

It can be done like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM