Skip to content

Instantly share code, notes, and snippets.

@robmint
Last active December 8, 2015 01:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robmint/513c5aa1286c8294d101 to your computer and use it in GitHub Desktop.
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.
// 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