1

I need to create an array initialized to the length of an object. Then be able to insert new data into an index within the array.

Code example:

$scope.holder = new Array($scope.x.length);
$scope.holder[0].new_data = response.data;

However the above will give error:

TypeError: Cannot set 'new_data' of undefined

How can this be if I specified the size of the array? Is the array not meant to have three objects in it. How can I solve this problem?

1
  • $scope.holder[0] is not defined yet, array has three undefined items Commented Nov 13, 2015 at 14:56

2 Answers 2

3

In this case first [0] element in Array must be Object because now it is undefined and you can not assign property to undefined, you need create empty Object ({}) and then assign properties to it

$scope.holder = new Array($scope.x.length);
$scope.holder[0] = {};
$scope.holder[0].new_data = response.data;
Sign up to request clarification or add additional context in comments.

Comments

3
$scope.holder = new Array($scope.x.length);
$scope.holder[0] = {'new_data':  response.data};

UPD: Or you can create array of objects

$scope.holder = Array.apply(null, Array($scope.x.length)).map(function () { return new Object(); })
$scope.holder[0].new_data = response.data;

1 Comment

Works aswell thank you! ai jai jai such silly things

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.