1

I have an object that contains an array and a couple of other values that I need to pass to the backend, but the backend needs to receive it as an array of objects. I fill in an array ($scope.student) by using checkboxes and the other values (docentid, vakid, klasid) by clicking on a field.

The object with the array and values:

$scope.user = {
studentid: [$scope.student],
vakid: '',
klasid: ''
};

The mapping function:

var dataToSend = [$scope.user.studentid].map(function(s) { 
    return { 
        vakid: $scope.user.vakid, klasid: $scope.user.klasid, studentid: s 
    }; 
});

Right now, when I log user, I see:

Object {studentid: Array[5], //Amount of results checked
vakid: "Alfreds Futterkiste", 
klasid: "Berlin"}

I would like to make it into an array of multiple objects, so every object will have the unique values of the array, vakid and klasid. The mapping function returns an empty array with vakid, klasid and studentid empty.

What am I doing wrong?

1
  • can you please show your html code Commented Nov 30, 2015 at 9:45

1 Answer 1

2

You don't want [$scope.user.studentid].map, but $scope.user.studentid.map.

var $scope = {};
  
$scope.user = {
  studentid: [1, 2, 3, 'a', 'b', 'c'],
  vakid: 'vak',
  klasid: 'klas'
};


var dataToSend = $scope.user.studentid.map(function(s) {
  return {
    vakid: $scope.user.vakid,
    klasid: $scope.user.klasid,
    studentid: s
  };
});

d = document.getElementById('result');
console.log(d)
d.innerHTML = JSON.stringify(dataToSend);
<div id="result"></div>

You want to actually map over the values in the array $scope.user.studentid, the other version ([$scope.user.studentid].map) maps over an array which wraps the array, it looks like this:

[[1, 2, 3, "a", "b", "c"]].map(/*...*/)

Calling map there is not giving your intended result.

Also of relevance, $scope is not defined correctly in your example. You can't set the user property of $scope before it exists (as you try to do with $scope.user = .... You can define as in my example, or as follows:

var $scope = {
  user: {
    studentid: [1, 2, 3, 'a', 'b', 'c'],
    vakid: 'vak',
    klasid: 'klas'
  }
};
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you. I see my mistake. But now when I try to run the code, it tells me $scope.user.studentid.map is not a function, which is surprising because it does work in your code. I am using AngularJS, do I need to inject mapping?
Look at the way I define the variable $scope. First I declar var $scope = {} then set the user property.
I found what was wrong. It wouldn't work, because my studentid array is empty when I load the page, so I put the mapping function into a function and I'll call it when the array is filled. Thanks for the help!
@Lok-KwanFoo Yes, mapping over [] is [] :). Glad you found your solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.