Dzieniu Dzieniu - 1 year ago 55
Javascript Question

Push data to object angularjs

I want to make tab of object, and pass to this tab values of another object using for loop. My tab of object:

data4 = [{meal_id : '' ,amount : '' }]

for loop:

for i in [0...$scope.mealsList.length]
data4[i].meal_id = $scope.mealsList[i].id
data4[i].amount = $scope.mealsList[i].amount

is tab of objects, which i want to copy.

Now i have an error:

Cannot set property 'meal_id' of undefined

Can You tell me, what am i doing wrong?

ps: sorry for my language skills, hope you understand all.


You iterate over the length of $scope.mealsList but get the values from data4. If those are not the same length (which seems to be the issue) you will get undefined when dereferencing data[i].

I'm not quite sure what you want to do, but it seems like you want to modify $scope.mealsList into data4 since you are replacing all values of data4.

In that case you could just modify the values in the mealsList to what you want and set data4 to it.

var result = map($scope.mealsList, function(item) { return { meal_id:, amount: item.amount };});
console.log('mapped: ', result);
data4 = result;

function map(arr, fn) {
  var res = [];
  for (var i = 0; i < arr.length; ++i) {
  return res;