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
Your issue is that you're referring to the same obj in memory and thus modifying both objects. A quick fix to this is to move your object declaration into the foreach loop, so you have your own unique reference to each object (not the same).
See working example below:
function getArrayObjForKeys(keys, source, desiredKeys) {
let arrayObj = []
source.forEach(function(val, ind) {
let obj = {}; /* Move into foreach */
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;
}
var source = [{
'country': 'USA',
'descr': 'United States'
}, {
'country': 'UK',
'descr': 'United Kingdom'
}];
var countryList = getArrayObjForKeys(['country', 'descr'], source, ['value', 'label']);
console.info(countryList);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With