Thursday, 29 August 2013

Using user specified arguments as keys in Javascript

Using user specified arguments as keys in Javascript

I have data coming back from an API as JSON. In this there is a results
array with result object/hashes with between 5 and 9 keys - id, url,
title, type, that sort of thing.
If I want to strip out the unnecessary stuff and return an array of
results with just title and url, I can do this:
function getTitleAndUrl(yourDataObject){
var results = yourDataObject.results;
var len = results.length;
var out = [];
for(var i = 0; i < len; i++ ) {
out.push({
title: results[i].title,
url: results[i].url
});
}
return out;
};
And I get all the results with just title and url.
How could I make it so that some arguments passed into a function become
the equivalent of 'title' and 'url'? The idea is like this:
function getSpecificData(yourData, arg1, arg2){
var results = yourData.results;
var len = results.length;
var out = [];
for( var i = 0; i < len; i++ ){
out.push({
arg1: results[i].arg1,
arg2: results[i].arg2
});
}
return out;
}
Where arg1 and arg2 could be title, url like the previous example or id,
description etc.
Any help greatly appreciated.

No comments:

Post a Comment