Last active
December 8, 2015 01:26
-
-
Save robmint/513c5aa1286c8294d101 to your computer and use it in GitHub Desktop.
Adds lists to an object, pushing to a list if a known key is specified.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// works well with querystring.stringify to produce GET parameters | |
function objectArrayPush(data, key, value) { | |
if (typeof data[key] != 'undefined' && data[key] instanceof Array) { | |
// EXISTS: pushing onto list | |
data[key].push(value); | |
} else { | |
// CREATING: pushing onto list | |
data[key] = []; | |
data[key].push(value); | |
} | |
return data; | |
} | |
var data = {}; | |
console.log(objectArrayPush(data, 'foo', 'bar')); | |
console.log(objectArrayPush(data, 'foo', 'baz')); | |
console.log(objectArrayPush(data, 'bob', 'blip')); | |
console.log(objectArrayPush(data, 'foo', 'womp')); | |
/* | |
Output: | |
{ foo: [ 'bar' ] } | |
{ foo: [ 'bar', 'baz' ] } | |
{ foo: [ 'bar', 'baz' ], bob: [ 'blip' ] } | |
{ foo: [ 'bar', 'baz', 'womp' ], bob: [ 'blip' ] } | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment