简体   繁体   中英

How can I create a new object from an array and an already existing object?

I am trying to create an object with modified property name from an already existing object and array.

var ExistingObj = {'123' : 50, '456' : 60, '789' : 90}; 
var idsArr = ['123', '456', '789'];  

I want to create an array of objects with the following content:

var newArr = [{id : '123', amount: 50}, {id: '345', amount: 60}, {id:'789' : 90}];  

I tried mapping it like this and it didn't work:

var existingObj = {'123' : 50, '456' : 60, '789' : 90}; 
var idsArr = ['123', '456', '789'];  


function formatArr(idsArr, existingObj){
 var obj = {}; 
 var container = [];

 _.map(idsArr, function(id){
  obj.id = id;  
  obj.amount = existingObj[id];     
  container.push(obj); 
 });
  return container;
}

and the result was:

container = [{'id' : '789', 'amount' : 90}, {id : '789', 'amount' : 90}, {id:'789', 'amount' : 90}];  

Any ideas?

Your current approach reuses the same object ( var obj = {}; ) within _.map function, as it's defined outside the _.map call. So at each step you modify the same object , then push it into container variable. Again. And again. And again.

That's why you'll get an array of identical records - they are, in fact, references to the same object.

Obviously, that's wrong. But what's even more wrong is using push inside _.map function: the key purpose of that function is building an array based on some other collection, and there's no need to add your own code to do that. That's how it can be written:

function formatArr(idsArr, existingObj) {
  return _.map(idsArr, function(id){
      return {
        id: id,
        amount: existingObj[id]
      });
  });
}

As a sidenote, using _.map without storing its result is almost always a logical error. If you don't care about results of iteration, use _.each .

Thanks for the info! I was able to make it work this way because I was calling it in another function:

function formatArr(idsArr, existingObj, fn){
  var newArr = _.map(idsArr, function(id){
    return {id: id, amount: existingObj[id]}
  });
  fn(newArr);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM