Reputation: 159
For that code below the output of ins (lets assume the value of keys are summer, spring, fall, winter) is:
['req.body.summer, req.body.spring, req.body.fall, req.body.winter']
What i want is remove the string after the replace command, so i can insert it to my SQLite query. So the output must be:
[req.body.summer, req.body.spring, req.body.fall, req.body.winter]
Im just new into programming so please bear with me. Thank you!
var arr = '';
Object.keys(input).forEach(function(key) {
arr += 'req.body.' + key + ', ';
});
var ins = [arr.replace(/,\s*$/, '')];
console.log(ins);
Upvotes: 0
Views: 62
Reputation: 351138
If the input is an array of strings, like 'summer', then do this:
var arr = input.map(key => req.body[key]);
// Sample input
var input = ['summer', 'spring', 'fall', 'winter'];
// Sample req:
var req = {
body: {
summer: 'sun',
spring: 'birds',
fall: 'leaves',
winter: 'snow'
}
};
var arr = input.map(key => req.body[key]);
console.log(arr);
If you prefer the function
syntax instead of =>
:
var arr = input.map(function (key) {
return req.body[key];
});
Upvotes: 1
Reputation: 2136
What you are looking for an Array of String Objects
var arr = new Array() ;var input= { 'spring':'a','summer': 'b'}
Object.keys(input).forEach(function(key) {
arr.push('req.body.' + key);
});
console.log(arr); // Prints ["req.body.spring", "req.body.summer"]
Upvotes: 1
Reputation: 7117
Try this...
Just declare arr
as an array and Push the values into it.
var arr = [];
var input = ['summer', 'spring', 'fall', 'winter'];
(input).forEach(function(key,value) {
arr.push('req.body.' + key);
});
console.log(arr);
Upvotes: 1