Hi I have below code in my project. The problem is the last item is being pushed to an array instead of each item.
JS Function
function getArrayObjForKeys(keys, source, desiredKeys) {
let arrayObj = [],
obj = {};
source.forEach(function(val, ind) {
keys.forEach(function(v, i) {
(function(v) {
if (val.hasOwnProperty(v)) {
let desKey = desiredKeys[i];
obj[desKey] = val[v];
}
}).call(this, v);
});
arrayObj.push(obj);
});
return arrayObj;
}
// Invoking function as below
// **************************
var source = [{
'country': 'USA',
'descr': 'United States'
}, {
'country': 'UK',
'descr': 'United Kingdom'
}];
var countryList = getArrayObjForKeys(['country', 'descr'], source, ['value', 'label']);
console.info(countryList);
Desired Output
[{'value':'USA','label':'United States'},{'value':'UK','label':'United Kingdom'}]
Plunker
https://next.plnkr.co/edit/3SKbaJo9r5QX8hex?open=lib%2Fscript.js