Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The last item is being pushed to Array (Javascript)

Tags:

javascript

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

like image 933
Devansh Avatar asked Jan 22 '26 08:01

Devansh


1 Answers

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);
like image 160
Nick Parsons Avatar answered Jan 23 '26 22:01

Nick Parsons