Reputation: 1238
I want to loop over a list of entitlements and create a concatenated json array. I want to loop over several data arrays and concatenate the ones that the user is entitled to.
const ROOSEVELT = require("./content/roosevelt") // these are .js arrays
const AMBITION = require("./content/ambition")
const CHAUCER = require ("./content/chaucer")
// beginning main function
exports.function = function (searchTerm, searchAuthor, searchQOTD) {
var entitlements = GET_REMOTE.checkEntitlements()
// returns json ["ROOSEVELT", "AMBITION", "CHAUCER"] from API server
var entitled_content = [] //empty target array
entitlements.forEach(function(item, array)
// loop over the list of entitlements
{ //this is where I want to concatenate the constants
// ROOSEVELT, AMBITION, and CHAUCER
// I need a one liner that adds each constant to the entitled_content array.
;});
// main function continues
Upvotes: 1
Views: 101
Reputation: 6491
You need to allow your imports to be looked up by way of a string since that is what checkEntitlements()
is returning.
An easy way to is add this imports to a lookup
object:
const ROOSEVELT = require("./content/roosevelt") // these are .js arrays
const AMBITION = require("./content/ambition")
const CHAUCER = require ("./content/chaucer")
const lookup = {
ROOSEVELT: ROOSEVELT,
AMBITION: AMBITION,
CHAUCER: CHAUCER
};
The downside with this is, you have the manually maintain your
lookup
object. If you want this to be automatically generated based on the files you are importing, you can look to use an NPM module such as require-dir, that'll return this object for you to use directly.const requireDir = require('require-dir'); const lookup = requireDir('./content');
Next, when you loop through your array of strings, I think you want your entitled_content
to be a flat list. If so, the concat
function is what you want.
Otherwise, entitled_content.push
would simply append your data to your array.
const ROOSEVELT = require('./content/roosevelt'); // these are .js arrays
const AMBITION = require('./content/ambition');
const CHAUCER = require('./content/chaucer');
const lookup = {
ROOSEVELT,
AMBITION,
CHAUCER,
};
exports.function = function(searchTerm, searchAuthor, searchQOTD) {
// returns json ["ROOSEVELT", "AMBITION", "CHAUCER"] from API server
var entitlements = GET_REMOTE.checkEntitlements();
var entitled_content = [];
entitlements.forEach(function(item) {
if (lookup[item]) {
entitled_content = entitled_content.concat(lookup[item]);
}
});
};
Upvotes: 1